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!

Download the source code here!

Sweet game! It still needs a lot of work, but this is a good foundation to work off of. Stay tuned for Part 3, where we will program our Mechanic # 2: The Player-controlled Paddle.

Thanks for reading, I hoped you learned something useful. If you have any questions or suggestions, feel free to leave me a comment!

Next up, Part 3: The Player Paddle.

Advertisements

58 comments on “Pong ~Part 2~ Programming the Ball

  1. Why did you make the function init(). You could simply write the code stage.addEventListener(Event.ENTER_FRAME, loop);
    after declaring the variables

  2. Ben Reynolds says:

    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.

    • Jeremy Sweetwood says:

      Do you have to make more layers or just one?

    • Michiel says:

      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?

  3. Lars says:

    When I test the game after writing the code for the ball i comes up with “Scene 1, Layer ‘Layer 1’, Frame 1, Line 11 1084: Syntax error: expecting rightparen before dot.” Can you please help

  4. n8studio says:

    This is great. You give very clear and easy to follow instructions and your comments are extremely helpful. Thanks!

  5. pipnina says:

    the script throws up an error that says.
    1120: Access of undefined property ball.
    i have checked my library and the object is called ‘ball’ so i dont see what the probelm is.
    please help.

    • Ben Reynolds says:

      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”.

      • hamishyoul says:

        Thanks dude! Your tutorials are sweet, I was stuck on this same dilemma..couldnt figure it out but thanks for the guidance! You rock! :)

  6. Lil Bro says:

    uh i dont know how make another action window for the codes

    • Ben Reynolds says:

      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.

  7. John.T says:

    I would like to know what the /2 does

    • Ben Reynolds says:

      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.

  8. fogest says:

    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 ?

  9. Sean says:

    What’s the difference between width and stageWidth?

  10. Lucas Ricci says:

    I don’t know why, but this error is appearing:

    Scene 1 1046: Type was not found or was not a compile-time constant: ball.

    I can sure to you that the ball is there, and I wrote everything correctly.
    Can you help me?

  11. Tyler says:

    5006: An ActionScript file can not have more than one externally visible definition :ballSpeedX, ballSpeedY

  12. Wingy says:

    Your explanations and expressions are very easy follow.
    Thanks for the upload!

  13. Michael says:

    Scene 1, Layer ‘Layer 1’, Frame 1, Line 13 1120: Access of undefined property ball.
    what does this mean?

  14. liviumine99 says:

    I have Flash Mx and it’s a problem with

    Scene=Scene 1, Layer=Layer 1, Frame=1: Line 6: ‘{‘ expected
    function init():void
    and

    Scene=Scene 1, Layer=Layer 1, Frame=1: Line 11: ‘{‘ expected
    function loop(e:Event):void

    What can do???

  15. dokabob says:

    For some reason after entering the code and testing the movie everything just stays still, I checked the code several times and then Copy/pasted your code in and still nothing will move.
    Why is this?

  16. dokabob says:

    (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

  17. Mike Riemer says:

    Symbol ‘ball’, Layer ‘Layer 1’, Frame 1, Line 35 1120: Access of undefined property ball

    What is this nonsense? it won’t go away the instance name and symbol name are both “ball”
    i cant fix it :/

  18. thejthorne says:

    I have done everything correctly, but when I compile it and run it, the ball is just..not there

  19. NewbieAlfon says:

    i’m sorry if this is a silly question, but since english is not my home language i don’t know what does right paren, colon, and left/right brace means?

  20. The Noob says:

    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.

  21. V Sprenger says:

    Hi there,
    Thanks for the tutorial, but I’m having a bit of trouble with one line of code. When I enter this:

    } else if(ball.x >= stage.stageWidth-ball.width/2){
    ball.x = stage.stageWidth-ball.width/2;
    ballSpeedX *= -1;
    }

    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!

  22. Anon26 says:

    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.

    Hope you can help.

    Regards,

    P.S: Remember you are awesome. :)

    • Ben Reynolds says:

      Hi there! I’m glad you’re enjoying the tutorials!

      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.

      Hopefully this will help. If it doesn’t, let me know.
      – Ben

      • Anon26 says:

        Thanks for reply!

        I will do so as instructed (by tomorrow), meanwhile I also left a comment on the Platform game tutorial as well. Please check it out.

        A million thanks for the work!!

  23. Excellent tutorial, thanks!

  24. Jono says:

    I have error “scene 1, Layer ‘Layer’,Frame 1, Line 21 1021:duplicate function definition.” sometimes the line is 16

  25. Armom says:

    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..

    • Ben Reynolds says:

      Hi! Thanks for reading, and sorry if the math is confusing you. If you’re looking to learn more math, I’d highly recommend watching some videos on http://www.khanacademy.org

      Note: Math is a huge subject, and it can take YEARS to learn a lot of math. But it’s definitely worth it, in the long run. Math is required to do a lot of things in programming.

  26. Juss Nevavuori says:

    Wow. Amazing tutorial, really getting me, the n00b programmer into programming.

    But I am getting the error “Symbol ‘ball’ 1026: Constructor functions must be instance methods”

    Why?

    • Juss Nevavuori says:

      Oh… Fixed… Had totally messed up my instance stuff and things, I don’t know what I had been doing but, it’s working now.

  27. John says:

    I don’t know if this is a problem with the site or my computer, but I see
    ball.width/2

    Other than that It’s a great tutorial and it all made sense once I downloaded the source code.

  28. adam gillard says:

    1120: Access of undefined property move. move.y+=ballSpeedY; what do i do?

  29. LarsOlsen says:

    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

  30. Annie says:

    I’ve Copy/Paste the code put it doesn’t work… the ball is moving put doesn’t bounce on the walls.. please help :)

  31. Liam says:

    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.

  32. Carrie says:

    I’m assuming here than ‘int’ (in the ball speed line) means ‘integer’… What’s the difference between using this or ‘number=2’? Would ‘number’ work in the same way?

  33. Carrie says:

    “ball.x += ballSpeedX” – Why does a plus and an equals need to be coded? (Why not just an ‘=’ for example?)

    Sorry, totally new to flash coding and I’m writing these as I read (rather than doing the rather less irritating ‘write it all in one comment’ method).

    :)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s