ActionScript 3.0 Ball Bounce

Navigation - Site Root :: Tutorial Home
Basics - Hello World :: Text IO :: Calculator :: If Statement
Games - Mouse Tracker :: Ball Bounce :: Maze :: Pong :: Ajax Style Demo
Techniques - Container Objects

  1. Start up Flash CS3
     
  2. Alter your canvas size and colour if you wish.
     
  3. On your stage, draw a shape such as a ball.
    Use the selection tool to select your shape.
    Press F8 to convert it to a symbol. Make sure you convert it into a movie clip.
    Give your shape an instance name such as myBall.
     
  4. Right click on Layer 1 and insert a new layer.
     
  5. Double click on Layer 2 and rename it to CodeLayer.
     
  6. In frame 1 of the CodeLayer, add this code.

    // ==== Listen for the enter frame event and run the myBallControl code each time. ====
    addEventListener(Event.ENTER_FRAME, myBallControl);

    // ==== GLOBAL VARIABLES FOR UP, DOWN, LEFT, RIGHT ====
    var ud:int = 1; // 0 = down. 1 = up
    var lr:int = 1; // 0 = left. 1 = right

    function myBallControl(event:Event)
    {
        // ==== HAS BALL HIT RIGHT EDGE? ====
        if (myBall.x > stage.stageWidth - myBall.width)
        {
            lr = 0;
        }

        // ==== HAS BALL HIT LEFT EDGE? ====
        if (myBall.x < 0)
        {
            lr = 1;
        }

        // ==== HAS BALL HIT BOTTOM EDGE? ====
        if (myBall.y > stage.stageHeight - myBall.height)
        {
            ud = 0;
        }

        // ==== HAS BALL HIT TOP EDGE? ====
        if (myBall.y < 0)
        {
            ud = 1;
        }

        // ==== X AXIS MOVEMENT ====
        if (lr)
        {
            myBall.x = myBall.x + 5; // x must be lower case
        }
        else
        {
            myBall.x = myBall.x - 5; // x must be lower case
         }

        // ==== Y AXIS MOVEMENT ====
        if (ud)
        {
            myBall.y = myBall.y + 5; // y must be lower case
         }
        else
        {
            myBall.y = myBall.y - 5; // y must be lower case
        }
    }

     
  7. Use CTRL+Enter to test the movie.
     
  8. The default 12 frames per second is a bit sluggish and jerky. Try increasing this value to 24 or 30 fps.
     
  9. Here you can download 70BallBounce.fla
     
  10. Here is the finished movie.