Change speed direction after hitting the boundary : Velocity « Animation « Flash / Flex / ActionScript






Change speed direction after hitting the boundary

 
package {
     import flash.display.Sprite;
     import flash.events.Event;
     import flash.geom.ColorTransform;
     import flash.geom.Rectangle;
     
     public class Main extends Sprite {
          public var speedX:int = 10;
          public var speedY:int = -10;

          public function Main() {
               addEventListener(Event.ENTER_FRAME, onEnterFrame);
               graphics.beginFill(0xFF, 1);
               graphics.drawCircle(0, 0, 25);
               graphics.endFill();

               var colorTransform:ColorTransform = new ColorTransform();
               colorTransform.color = Math.random()*0xFFFFFF;
               transform.colorTransform = colorTransform;
          }
          
          private function onEnterFrame(event:Event):void {
               x += speedX;
               y += speedY;

               var bounds:Rectangle = getBounds(parent);

               if (bounds.left < 0 || bounds.right > stage.stageWidth) {
                    speedX *= -1;
               }
               if (bounds.top < 0 || bounds.bottom > stage.stageHeight) {
                    speedY *= -1;
               }
          }
     }
}

        








Related examples in the same category

1.Velocity Animation
2.Calculating position based on velocity