Bits & Bytes

Creating a Simple Animation in Actionscript 3.0

In this example, I create a red rectangle the moves back and forth across the screen. The primary purpose of this example is to show how to create a callback function for animation. So, I will not bother to explain too much about the coordinate calculations that are used for motion.

To create an animation, I could use a Timer object to set an time interval for the animation speed. However, it is better to use the frame rate of the application for controlling the animation. In this manner, the speed of the animation can be altered via the “Properties” window, and should be set to a level that is appropriate for the complexity of the program. The typical setting that is currently used for Flash is 24 frames per second. In order to set a callback that is called every frame, we can use the event ENTER_FRAME, as shown below.

addEventListener(Event.ENTER_FRAME, NextFrame);

// Create rect for sprite and add to stage
var qRect:Sprite = new Sprite();
var uiColor:uint = 0x00c00000;
qRect.graphics.beginFill(uiColor);
    qRect.graphics.drawRect(0, 0, 100, 75);
qRect.graphics.endFill();
addChild(qRect);

// Variables for motion control
var uiX:uint = 0;
var uiDeltaX:uint = 4;
var kuiMaxX:uint = 220;

// Animation callback
function NextFrame(e:Event) : void {
	uiX = ((uiX + uiDeltaX) % (kuiMaxX + 1));
	qRect.x = uiX;
	if (uiX == kuiMaxX || uiX == 0) {
		uiDeltaX = (kuiMaxX - uiDeltaX);
	}
}

Here, we have the code to move a rectangle back and forth across the screen. The first line of code sets the function NextFrame() as a callback that responds to the event that is generated at the start of a frame. After this, we have some code that creates a Sprite, draws a red rectangle on it, and adds the Sprite to the stage so that it will be displayed. In the next, three lines, we initialize the variables that will control the motion of the rectangle. Finally, we define the callback function, NextFrame(), which may seem confusing. We want to focus on the fact that this function sets the x-coordinate of the Sprite, qRect.x, to control the motion, while the rest of the code is just used for calculating the value of x.

Tags: , , , , , ,

Michael Hall

By: Michael Hall

Leave a Reply

*

 

© 2007–2024 XoaX.net LLC. All rights reserved.