Flash CS3 Actioncript 3.0 Introduction

Flash CS3 Actioncript 3.0 Introduction

This tutorial on Programming Actionscript 3.0 describes in text what you will be taught in the FLASH CS3 VIDEO TIP – Introduction to Actionscript 3.0 Preview which demonstrates how to get your object to move to a specific point on the stage.

Say we have a MovieClip that we want to move around the stage. With Actionscript 3.0 we can move that MovieClip to wherever we want using using the programming language that is native to Flash CS3, ie, AS 3.0. Create a MovieClip ball_mc on its own layer, call that layer ball, and then create a new layer and call it actions. Click on frame one of the actions layer and open the Actions window.

In this tutorial we are going to create a timer and a function that will move the ball. Always use comments so that you know later what was going on and so that other people can follow your code.
Here is the code that you will put in the Actions window:

// create the Timer object
// set it to tick every 40 milliseconds
var myTimer:Timer = new Timer(40);
// add event listener to timer object 
// and tell it to listen for moveBall function
myTimer.addEventLister(TimerEvent.TIMER, moveBall);
// declare variables
// intitialise start to original position
var startX:Number = ball_mc.x;
var startY:Number = ball_mc.y;
// initialise end points to a number
var endX:Number = 400;
var endY:Number = 300;
// declare and initialise counter
var i:Number = 0;
// moveBall function
function moveBall(event:Event):void
	// we want to run the function ten times
	// check if counter is less than ten
	if(i < 10)
		// move ball
		ball_mc.x += (endX - startX)/ 10;
		ball_mc.y += (endY - startY) / 10;
		// trace end position
	// increment counter 

The code above will move the ball to the position (400,300). If we want to make the ball slower then you can test the counter to see if it has reached the number 20 and then halve the amount the ball moves in each loop. So these lines would appear thus:

// ....
if(i < 20)
	ball_mc.x += (endX - startX) / 20;
	ball_mc.y += (endY - startY) / 20;
// ...

Another way to slow it down would be to change the timer increment so that instead of it running every forty milliseconds it will run every eighty milliseconds. Like so:

var myTimer:Timer = new Timer(80);

So there are numerous ways that this animation can be slowed down or speeded up. You can change the amount that the ball moves every tick of the timer or you can change the amount the timer ticks over at. You can also change the number 10 or 20 to a variable called speed and then you only have to change it once when it is initialised:

 var speed:Number = 20;
 // ...
 if(i < speed)
	ball_mc.x += (endX - startX) / speed;
	ball_mc.y += (endY - startY) / speed;
	// ..	 

Flash CS3 Resources


Leave a Reply

Your email address will not be published. Required fields are marked *