O'Reilly logo

Essential ActionScript 3.0 by Colin Moock

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Velocity-Based Animation

In the Flash runtime, the specific timing of both scheduled screen-update checks and TimerEvent.TIMER events is not guaranteed. The Event.ENTER_FRAME event often executes later than the time scheduled by the designated frame rate, and TimerEvent.TIMER events often occur later than the time specified by a Timer object's delay variable.

These delays can result in unpredictable animation. To guarantee that a given object will travel a specified distance in a specified amount of time, we must set its position according to its velocity (i.e., its rate of speed in a particular direction). Example 24-10 shows the basic technique.

Example 24-10. Calculating position based on velocity

package { import flash.display.*; import flash.events.*; import flash.utils.*; // Moves an object a specified number of pixels per second, no matter what // the frame rate public class Animation extends Sprite { private var distancePerSecond:int = 50; // Pixels to move per second private var now:int; // The current time private var then:int; // The last screen-update time private var circle:Shape; // The object to animate public function Animation () { // Create the object to animate circle = new Shape(); circle.graphics.beginFill(0x0000FF, 1); circle.graphics.lineStyle(1); circle.graphics.drawEllipse(0, 0, 25, 25); addChild(circle); // Initialize timestamps then = getTimer(); now = then; // Register for notification of scheduled screen-update checks addEventListener(Event.ENTER_FRAME, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required