Creating a Bouncing Ball : Bounce « Animation « Flash / Flex / ActionScript






Creating a Bouncing Ball

 
package
{
import flash.display.Sprite;
import flash.events.Event;
public class Main extends Sprite
{
    private var ballOne:Sprite;
    private var ballTwo:Sprite;

    private var direction:int = 1;

    public function Main()
    {
        ballOne = new Sprite();
        ballOne.graphics.beginFill(0xff0000, 1);
        ballOne.graphics.drawCircle(0, 0, 30);
        ballOne.graphics.endFill();
        ballTwo = new Sprite();
        ballTwo.graphics.beginFill(0x0000ff, 1);
        ballTwo.graphics.drawCircle(0, 0, 30);
        ballTwo.graphics.endFill();

        addChild(ballOne);
        addChild(ballTwo);

        ballTwo.x = 200;
        ballOne.x = 300;
        ballTwo.y = 5;
        ballOne.y = 5;

        ballTwo.addEventListener(Event.ENTER_FRAME, bounce);
        ballOne.addEventListener(Event.ENTER_FRAME, bounce);
    }

    private function bounce(event:Event):void
    {
        var target:Sprite = event.target as Sprite;
        try
        {
            if (target.y == 199)
            {
                direction = -1;
            }

            if (target.y == 1)
            {
                direction = 1;
            }

            if (target.y < 200 && target.y > 0)
            {
                trace(target.y + " : " + direction);
                target.y += direction;
            }

        } catch(err:Error) {
            trace("ooops....");
        }
    }
}
}

        








Related examples in the same category