Recipe 11.4. Acceleration


Problem

You want an object to start moving slowly and then speed up over time.

Solution

Apply acceleration.

Discussion

Many people think of acceleration as simply speeding up. After all, when you want to go faster in your car, you step on the accelerator. A more scientific definition would be a change in velocity. Although this certainly encompasses increasing an object's speed, it also applies to slowing it down or changing its direction.

Acceleration requires an understanding of velocity as covered in Recipes 11.1 and 11.2. Acceleration also has a magnitude and direction, which can be represented as acceleration on the x and y-axes. With each frame or animation interval, the acceleration of each axis is added to the velocity on that axis, and then the velocity is added to the position, as in Recipe 11.1.

The following example uses the variables _ax and _ay for acceleration and _vx and _vy for velocity:

package {     import flash.display.Sprite;     import flash.events.Event;          public class Accel extends Sprite {         private var _sprite:Sprite;         private var _ax:Number = .3;         private var _ay:Number = .2;         private var _vx:Number = 0;         private var _vy:Number = 0;                  public function Accel(  ) {             _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 {             _vx += _ax;             _vy += _ay;             _sprite.x += _vx;             _sprite.y += _vy;         }     }     }

As you can see, the sprite starts out motionless and gradually picks up speed as it goes across the stage. Generally, since acceleration is additive, the acceleration values should start out small; velocity builds up quickly over time.

Also, similar to Recipe 11.2, you can start with a direction and magnitude for the acceleration force:

var angle:Number = 45; var accel:Number = .5;

Then convert this to acceleration on each axis:

var radians:Number = angle * Math.PI / 180; _ax = Math.cos(radians) * accel; _ay = Math.sin(radians) * accel;

Now you have values that you can add to the velocity.

It's worth noting that gravity is simply acceleration on the y-axis. You can create a gravity variable and set it to a constant value. Then add it to the y velocity on each frame, and you will have realistic gravity.

See Also

Recipes 11.1 and 11.2 for information on velocity .




ActionScript 3. 0 Cookbook
ActionScript 3.0 Cookbook: Solutions for Flash Platform and Flex Application Developers
ISBN: 0596526954
EAN: 2147483647
Year: 2007
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net