Make a bouncing ball with Flash

Make a bouncing ball with Flash

  In this tutorial we will learn how to make a bouncing ball when it hits the walls by using Actionscript to detect the collision

 

Step 1: Create a new flash document and press Ctrl-J to open the Document Properties box and set the dimensions to 400px width,300px height and a frame rate of 50 fps with a black background color

MakeABouningBallwithFlash1

 

Step 2: Download the ball image below and drag it onto your flash document.

60px-Soccer_ball

Step 3: Click on the ball to select it. Press F8 to open up the Convert to Symbol dialog. We will turn this image to a movie clip so selectMovie clip type, set the Registration at the center point and name it mc_Ball

MakeABouningBallwithFlash3

Step 4: Make sure the ball is still selected. Press Ctrl-F3 to open up the Properties tab if it hasn’t shown up yet. In the Instance Nameinput box type in mcBall, although we will not use this variant but it is a good habit to name an instance of an object right after we had created it (we will refer it by the this keyword, as you will see in the script below)

MakeABouningBallwithFlash4

Step 5:  Click on the ball to make sure it is being selected. Press F9 to open up the Actionscript tab and type in the code below:

onClipEvent(load) { xSpeed = ySpeed = 5; }
onClipEvent(enterFrame)
{
this._x += xSpeed; //Move the ball horizontally
this._y += ySpeed; //Move the ball vertically

//Bouncing the ball off of the wall on the right side. Because we selected center of the ball as the

// “registration” point so we have to minus with this._width/2

    if(this._x >= Stage.width-this._width/2)
{
//if the ball hits the right side
//of the screen, then bounce off
xSpeed *= -1;
}
if(this._x <= this._width/2)
{
//if the ball hits the left side
//of the screen, then bounce off
xSpeed *= -1;
}
if(this._y >= Stage.height-this._height/2)
{
//if the ball hits the bottom
//then bounce up
ySpeed *= -1;
}
if(this._y <= this._height/2)
{
//if the ball hits the top
//then bounce down
ySpeed *= -1;
}
}

We use the OnClipEvent(load), which is triggered when the clip is first loaded, to initialize the speed of the ball xSpeed and ySpeed.

All the if clauses are used to check if the ball is coming to the borders of the wall. You can read the comments inside the code to understand how it works.

Finally, press Ctrl-Enter to test the result.

One thing I want to mention is if you don’t select the center of the ball as the “registration” point then you have to minus (or compare) with this._height (or this._width)