Calculating position based on velocity : Velocity « Animation « Flash / Flex / ActionScript






Calculating position based on velocity

 
package {
  import flash.display.*;
  import flash.events.*;
  import flash.utils.*;
  public class Main 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 Main(  ) {
      circle = new Shape(  );
      circle.graphics.beginFill(0x0000FF, 1);
      circle.graphics.lineStyle(1);
      circle.graphics.drawEllipse(0, 0, 25, 25);
      addChild(circle);

      then = getTimer(  );
      now  = then;

      addEventListener(Event.ENTER_FRAME, enterFrameListener);
    }

    private function enterFrameListener (e:Event):void {
      then = now;
      now = getTimer(  );
      var elapsed:int = now - then;
      var numSeconds:Number = elapsed / 1000;

      var moveAmount:Number = distancePerSecond * numSeconds;


      circle.x += moveAmount;
    }
  }
}

        








Related examples in the same category

1.Velocity Animation
2.Change speed direction after hitting the boundary