O'Reilly logo

ActionScript 3.0 Cookbook by Joey Lott, Darron Schall, Keith Peters

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

Moving an Object

Problem

You have a graphic in a sprite and you want to animate it, giving it some motion.

Solution

Decide on a velocity for the x or y-axis (or both), and add that velocity to the object’s position on each frame or animation interval.

Discussion

Velocity is often incorrectly defined as speed. However, velocity also includes a direction factor. For example, “10 miles per hour” is speed, but “10 miles per hour due north” is a velocity. If you are dealing with velocity on the x or y-axis, the direction is inherent. A positive x velocity is to the right; negative to the left. Likewise, a positive y velocity is down, and negative is up.

The first example defines the x velocity, _vx, and sets it to 3. Since this example uses the enterFrame event for animation, the object will move three pixels to the right on each frame:

package {
    import flash.display.Sprite;
    import flash.events.Event;
    
    public class Velocity extends Sprite {
        private var _sprite:Sprite;
        private var _vx:Number = 3;
        
        public function Velocity() {
            _sprite = new Sprite();
            _sprite.graphics.beginFill(0x0000ff, 100);
            _sprite.graphics.drawCircle(0, 0, 25);
            _sprite.graphics.endFill();
            _sprite.x = 50;
            _sprite.y = 100;
            addChild(_sprite);
            addEventListener(Event.ENTER_FRAME, onEnterFrame);
        }
        
        public function onEnterFrame(event:Event):void {
            _sprite.x += _vx;
        }
    }    
}

If you set _vx to -3 instead, you’ll see that it goes in the opposite direction. You can also add in some y velocity by creating a _vy variable, giving it a value, ...

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