How to make a bouncing ball in ActionScript

If you’re looking to make a game where a ball bounces off the edge, the math is pretty easy.

What are we making?

Here’s what we’re after. Just a little ball bouncing around the stage.

Sorry, either Adobe flash is not installed or you do not have it enabled

We’re going very simple, both with code and graphics.

Starting up

Create a new ActionScript project. I kept mine at the default frame rate on 24 frames per second and the default stage size of 550×400 pixels.

Next create a new movie clip symbol named Ball_mc. Make sure that you export the symbol for ActionScript. You want to draw a circle with the registration point at the center of the circle.

Pong Ball

Ball symbol with registration point at the center

Go back to the stage and press F9 to insert code on frame 1.

The Code

import flash.events.Event;

stage.addEventListener(Event.ENTER_FRAME, eFrame);

var ball:Ball_mc = new Ball_mc();
ball.x = stage.stageWidth / 2;
ball.y = stage.stageHeight / 2;
ball.xSpeed = 4;
ball.ySpeed = 7;
stage.addChild(ball);

function eFrame(evt:Event):void {
	ball.x += ball.xSpeed;
	ball.y += ball.ySpeed;

	if (ball.x = stage.stageWidth - ball.width / 2) {
		ball.xSpeed *= -1;
	}
	if (ball.y = stage.stageHeight - ball.height / 2) {
		ball.ySpeed *= -1;
	}
}

The Explanation

Line 3 adds the event listener to Event.ENTER_FRAME.

Lines 5 – 10 create an instance of Ball_mc named ball, place it in the center of the stage, create two new variables to hold the x and y speeds, and adds the instance to the stage.

Lines 12 – 22 are the eFrame callback function associated with the event listener.

Lines 13 & 14 move the ball by changing its x and y position by xSpeed and ySpeed respectively.

Line 16 checks to see if the ball has gone either off the left edge or right edge. If it has, line 17 multiplies the xSpeed by -1 so that the ball will start moving in the opposite direction in the next frame. Adding or subtracting ball.width / 2 is because the registration point of the Ball_mc symbol is in the center.

Lines 19 – 21 do the same except for the top and bottom edges.

What’s next?

It’s fairly short to take this example and have the ball bounce off of two paddles. You’ll just need to add a couple of conditions to the frame handling callback to check to see when the ball collides with the paddles.

Maybe instead of bouncing off of the right and left edges you want to add points to a player and have the ball go back to the center.

Maybe the ball should get faster with each bounce.

It’s pretty much your call.

Tagged with: , ,
Posted in Coding

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>