Pong ~Part 2~ Programming the Ball

Welcome to Part 2 of the Actionscript 3 Flash game tutorial series for Pong!

Make sure you check out Part 1 if you haven’t done that already. And if you are completely new to programming, my Getting Started tutorials are the place for you.

Enough talk, let’s code.

Step Two: Program the basic game loop and the ball

First things first, we need to name each instance of our game pieces — this is what we’ll use to refer to each object in the code. Name the paddle on the left “playerPaddle” (no quotes), the paddle on the right “cpuPaddle”, and the ball can just be named “ball”.

OK, now open up the actionscript panel (Window -> Actions), and click anywhere on the background so that nothing on the stage is selected. Flash is now set up so that the code that you type into the panel will run when we compile the game.

So, we’re ready to add code… where’s the best place to start?

I strongly recommend planning out in your head what the game needs to do before you start programming. I boiled our game down to 3 main mechanics, and we can add any extra features afterwards:

The ball needs to move at a constant rate, and bounce off walls and paddles

The playerPaddle needs to move up and down when we control it with the up and down arrow keys

The cpuPaddle needs to move up and down automatically to try to block the ball

One thing in common between all of these actions is that they need to be happening every single frame, not just a one-shot deal. So let’s begin with the main game loop.

init(); //call this function once, at the very beginning, to initialize everything
function init():void
{
stage.addEventListener(Event.ENTER_FRAME, loop); //every time our game enters a new frame (60 times per second), this event listener will fire and our game will loop
}
function loop(e:Event):void
{
}

Very basic, but everything that we code inside the loop function will happen over and over again.

Let’s start with our first game mechanic: the ball. This code will make it move.

var ballSpeedX:int = -3; //how fast the ball is moving left and right
var ballSpeedY:int = -2; //how fast the ball is moving up and down (negative = up)
init();
function init():void
{
stage.addEventListener(Event.ENTER_FRAME, loop);
}
function loop(e:Event):void
{
ball.x += ballSpeedX; //each frame, we add the ballSpeedX to the ball's x position
ball.y += ballSpeedY; //we do the same with the ballSpeedY and the ball's y position
}

If you compile the game now (Control -> Test Movie) you should see the ball zoom off of the upper-right corner of the screen.

That’s an improvement, but we want our ball to bounce off of every wall so that it stays on the screen. Try this:

var ballSpeedX:int = -3;
var ballSpeedY:int = -2;
init();
function init():void
{
stage.addEventListener(Event.ENTER_FRAME, loop);
}
function loop(e:Event):void
{
ball.x += ballSpeedX;
ball.y += ballSpeedY;
//because the ball's position is measured by where its CENTER is...
//...we need add or subtract half of its width or height to see if that SIDE is hitting a wall
//first check the left and right boundaries
if(ball.x <= ball.width/2){ //check if the x position of the left side of the ball is less than or equal to the left side of the screen, which would be 0
ball.x = ball.width/2; //then set the ball's x position to that point, in case it already moved off the screen
ballSpeedX *= -1; //and multiply the ball's x speed by -1, which will make it move right instead of left
} else if(ball.x >= stage.stageWidth-ball.width/2){ //check to see the right side of the ball is touching the right boundary, which would be 550
ball.x = stage.stageWidth-ball.width/2; //reposition it, just in case
ballSpeedX *= -1; //multiply the x speed by -1 (now moving left, not right)
}
//now we do the same with the top and bottom of the screen
if(ball.y <= ball.height/2){ //if the y position of the top of the ball is less than or equal to the top of the screen
ball.y = ball.height/2; //like we did before, set it to that y position...
ballSpeedY *= -1; //...and reverse its y speed so that it is now going down instead of up
} else if(ball.y >= stage.stageHeight-ball.height/2){ //if the bottom of the ball is lower than the bottom of the screen
ball.y = stage.stageHeight-ball.height/2; //reposition it
ballSpeedY *= -1; //and reverse its y speed so that it is moving up now
}
}

It really isn’t too complicated, but I’ve added a ton of comments so you know exactly what is happening. In order to find the x value of the right side of the screen we used the stageWidth property of the stage, and likewise we used the stageHeight property to find the y value of the bottom of the screen. If the ball’s position is ever greater or less than a specific side of the screen, the speed will reverse and it will bounce off the wall.

Compile it… and… it’s like you have magic invisible borders on your screen!

I included the init() function partly just because it’s good practice — in more complicated games, sometimes setting up can be a lot more complicated, and adding a function to contain it all will keep you better organized. I agree that in this particular game it is a bit redundant, but it doesn’t do any harm.

Init() isn’t great practise. You’d be better off putting that code in the constructor of you main movieclip. AS3 is object oriented, yet here you make absolutely no use of that. Sure for small programs OO is more of a pain but once you get your hands dirty it’ll really pay off.

See, I only have a knowledge of java in a blueJ environment( a knowledge not even pertaining to applet commands, that is). Java is required for my class 11 and 12 too, so it doesn’t make sense in learning a new language. Can I implement the BlueJ packages to the Macromedia Flash, to make games like pong? Or is my only choice Action Script?

Glad you fixed your problem, and don’t worry about it — I have gotten SO many little bugs like that over my time programming. Annoying, but after awhile you naturally make them less and less just from practice.

I think your problem is probably that you didn’t set the *instance name* of the ball to “ball”. Even if you create an object in the library called “ball”, you need to drag one onto the stage, click on it to make it active, and then use the Properties Panel to set the name to “ball”, in the section called “instance name”.

Use the “Window” menu, and choose “Actions”. A text-editor window should pop up. If it won’t let you type anything, click on the first frame in the timeline to select it. Then just type the code into the actions window.

When I created the ball object, I set it’s center point to be the center of the object. This means if I write ball.x, I will get the x position of the center of the ball. But a ball bouncing off of a wall doesn’t bounce from it’s center, it bounces from it’s side. By adding or subtracting half of the ball’s width, I was able to find the x position of the side of the ball, to use when colliding with the side of the screen. The /2 is just what I used to get half of the width.

I understand everything here but, the if statements conditions. The Else if’s make sense how it’s checking the stage width for right and bottom but how is the left and top being checked? From what I see your saying in the code is : if the balls x is less then or equal to half of the balls width then make the balls x half of the balls width and then flip the direction. Do I have this right? It just seems a bit weird to me how this is working. Could you explain this to me ?

(May be a double post because I don’t think the last one went through)
For some reason after running the game nothing moves, I looked over the code several times and then copy/pasted yours in, and still nothing works

Hello i am new to flash and this is my first game that i am making, i have put in all the code and the ball moves fine but i don’t no were to put in the loop code. At first i thought it did not matter if i put it in or not, but then i read the third tutorial and i noticed it was important so can someone please help me and tell me where to put it, Thanks The Noob.

I get the error message: “1087: Syntax error: Extra characters found after end of program.”
I’ve tried many differnt things but always end up with this error that keeps the ball from moving. Any suggestions would be appreciated! Thank you!

Hi there,
firstly, Its very awesome tutorial. Kudos for doing it.
What i essentially liked (till this point) was the part of getting started where you point out the general layout of any game. This thing is missing from many other tutorials on the web, and was exactly what I was looking for.

Secondly I have a problem.

The ball in my case is just behaving rather erratically. That is acting like its repeatedly hitting the wall. sort of like headbanging on the wall. When in test mode, if I click on Control, and “step forward one frame”, the animation resume as intended.

where it gets weird is, even when I copy your code exactly, it still occur.
If I download your source code and run it. It works fine.
But if I copy the very code into my project, I still have to click on “step forward one frame” for ball to act correctly

What I fail to understand is why the same code would act differently in two projects, when they are apparently the same.

I understand your frustration. Theoretically, the same code should always do the same thing.

I can’t be sure, but perhaps there’s something else in you project file (besides the code) that is acting funky and causing problems. Movieclips, instance names, project settings, etc. Perhaps you could try creating a fresh Flash project, and copying your code into it, and adding new movieclips. That’s all I can think of right now.

I am not understanding the MATH you did :(
Please help me to understand the math.. I understand everything expect the mathemetical parts.. Please explain me or show me some ways to be good in that math parts..

Hi :)
Im a completly new to programming and i was just wondering…
so far everything seems to run great, iow no program errors, but the ball just moves from side to side..
it doesnt seem like the ball is registrating the x and y ball speeds or something?
any ideas? :P

Hey i wondered if you could tell me how to increase the ball speed after scoring 3 points or so. I’m need to make my game have ‘levels’ so if you can help me increase the ball speed or the cpu paddle would be great
oh and great tutorial by the way.