Welcome back to the AS3 Game Tuts pong tutorial series. So far in this series we’ve created a working pong game complete with a ball and two paddles. In this tutorial we are going to add a scoring system to the game.
As always, if you haven’t read the rest of the series yet I highly recommend starting with the beginning.
Part 1: Setting up the Project
—
Keeping track of score
Pong traditionally has 2 score values: the player’s score and the computer’s score. This is actually super-simple for us to create! Basically a score value is just a variable that holds a number. At the start of the game we set the variable to 0, and every time the ball hits the left or right walls we add 1 to the score of whoever scored the point.
First off, let’s create the playerScore and cpuScore variables, which will be integers. Add this right below the other variable declarations.
var playerScore:int = 0; var cpuScore:int = 0;
That was easy enough. Now let’s revisit some old code from Part 2 of this series (when we programmed the ball bouncing off the walls). Logically, whenever the ball hits the right edge of the screen the player will score 1 point. And whenever the ball hits the left edge of the screen the computer scores a point.
Modify this code from the main game loop…
if(ball.x = stage.stageWidth-ball.width/2){ ball.x = stage.stageWidth-ball.width/2; ballSpeedX *= -1; }
…so that it looks like this:
if(ball.x = stage.stageWidth-ball.width/2){ ball.x = stage.stageWidth-ball.width/2; ballSpeedX *= -1; playerScore++; //increase playerScore by 1 }
Also, modify your other code by adding cpuScore++, in the same way you added playerScore++.
if(ball.x <= ball.width/2){ ball.x = ball.width/2; ballSpeedX *= -1; cpuScore++; //increase cpuScore by 1 }
As you can see, in order for the player to score a point we type in “playerScore ++”, and we type in “cpuScore ++” when the computer scores a point. Pretty self explanatory.
Creating the text fields
So if you test the game now you’ll notice that although we did add the code for the scoring system, nothing has visually changed. We still need to add a display for the scores, so the you can visibly see how many points each side has. In order to do this we need to first move back over to the stage of Flash and build a text game object for each score.
Use the Text Tool (T) to create a text field on the screen. In it, type: Player Score: 0 (as shown above). Select it, and in the top of the properties panel switch the text field from Static Text to Dynamic Text. This changes it from just ordinary text into a game object which we can modify using code. It also lets us give the text an instance name, so name yours “playerScoreText”.
The rest of the formatting doesn’t really matter, except to make it look differently. Feel free to either use the formatting shown in the image above, or to format the text field on your own. Personally I set the color to white, used a size 18 Courier font, set the position to (0,0) and set the width to 200 so that the text field has extra space in case the score takes up multiple digits.
Now we must do the same for the cpuScore.
Basically just repeat what we did for the playerScoreText: Create a text field, type in: CPU Score: 0, set it to Dynamic Text, give it the instance name cpuScoreText, and format it like you did the last one. I positioned my cpuScoreText at (400,0) and gave it a width of 150.
Putting it all together
So now that the text fields are all set up we can return to the code and put everything together.
Create a new function in your code window called updateTextFields:
function updateTextFields():void { playerScoreText.text = ("Player Score: " + playerScore); cpuScoreText.text = ("CPU Score: " + cpuScore); }
Every time this function is called the we modify the text property of the playerScoreText and cpuScoreText. We set the text equal to the score name (in quotes) plus the score variable (no quotes). This function is complete.
All we have to do to make this work is to call updateTextFields() anytime someone scores a point. So go back to the code in the game loop, and add those lines:
if(ball.x = stage.stageWidth-ball.width/2){ ball.x = stage.stageWidth-ball.width/2; ballSpeedX *= -1; playerScore++; //increase playerScore by 1 updateTextFields(); }
And now, ladies and gentlemen, the scoring system is done!
Get your sourcecode hot off the press, HERE.
Please let me know what other features you would like to see implemented in this game in future tutorials. Would you like to add winning and losing? A title screen? Sound effects and music? More realistic physics and AI? Either leave a comment, or drop me an email me at: AS3GameTuts@Gmail.com.
Stay tuned for more Pong tutorials, as well as a new series on how to create an art-based platformer.
Subscribe to the AS3GameTuts RSS feed to stay up-to-date on the latest and greatest tutorials.
Awesome tutorial! But one question, on the scoring system, after anyone scores once their score text is black so I cant see it. Any suggestions?
Did you set the text color to white when you drew the text box on the stage in Flash (you can change the color in the Properties panel)? If that doesn’t work, you could always draw a white box behind each of the text boxes so that any color would be visible.
Hey Ben,
Thanks for the tutorial. I was actually hoping that you could help me with an urgent problem. For me when the score changes the text doesn’t go black but actually disappears (just the number 0).
I get the following error…
“Fonts should be embedded for any text that may be edited at runtime, other than text with the “Use Device Fonts” setting. Use the Text > Font Embedding command to embed fonts.”
I’m new to flash and i don’t think I’m embedding the font correctly. Could you help?
Go to text > font embedding.
Choose the font family/families you are using. tick in All at ‘character ranges’.
Give it a name (doesnt really matter) and now press the ‘+’ button and press OK.
Now publish your game and the error should be gone if you added the right fonts :)
In my case, I had to embed my font. I’m not sure if it’s only because it isn’t a typical font (I used Ubuntu Mono), but you just need to select the text menu on the toolbar and go to (Font Embedding…) and select the font you’re using as well as the necessary characters (saves room, I guess). Worked for me.
Awesome tutorial man! Ýou make it all look so easy!
But ehm, would it be hard to add a starting menu with a start button and maybe a resut button at the end? I hope you read this soon cause I need it before tomorrow. If you don’t: no problem, you helped me a lot anyway
Sorry I never got around to making the title screen and reset button. It’s a good idea, and I still might add it as a Part 7 sometime in the next month.
Awesome pong game tutorial. It help me a lot about gaming AS3 codes.
If you want I can help you with the starting menu and a start button.
Please reply back. =)
hey, your counting doesnt work in your codelink, the 0 dissapears
If I’ve made an error, I’d love to fix it… but I can’t tell exactly where you are referring to. Can you give me a little more information? Thanks for alerting me :-)
It’s the font embedding. Click on the textfield, next to style there is a button called ‘Embed…’. Click on it, at ‘character ranges’ tick uppercase, lowercase and numerals. Press OK now, and the text should now work fine!
Hey buddy, I still can’t fix it. The number doesn’t show. What should I do?
You need to click the + button at the top them select Punctuation and Basic Latin then click OK.
Go Text -> Font Embedding first
Thanks Alot now its really working :)
Your problem might be that you’re expecting the the text to come up straight away. In that case you need to put up the text manually as well, to start your scoreboard off.
Although it sounds like you’ve just made a slight error in the tutorial. I don’t think anyone else is finding your problem.
Turns out you were right. My bad. :B Ignore my previous post.
if I or the cpu scores a point, the 0 doesnt change into 1 but into nothing on top of the screen, also it might be becouse of this error:
Output says:
Fonts should be embedded for any text that may be edited at runtime, other than text with the “Use Device Fonts” setting. Use the Text > Font Embedding command to embed fonts.
Do you have the text objects set as classic > dynamic? I changed mine from that to TLF > Editable and it fixed the problem. Hope it helped :)
OK, thanks, that makes sense to me now. Just like the error message says, I forgot to embed to font I used into the text field of the project. It runs fine on my computer because my computer already associates that font with what I used in the project, but for anyone running a different setup the font will be unknown, and just disappear.
I’ll try to fix it ASAP. Thanks again.
It’s doin the same thing for me. How do I fix this?
Nevermind I got it!!! Awesome!
Thanks so much!
Thanks for teaching this. You are too good in it. But can you also put in it to control the Paddle with the keyboard.
Thanks, I’m glad you found it helpful! I’ll try to add on another tutorial part later with the keyboard controls when I have time.
whats the cpu score adding code? mine wont count computers points
Wow, thanks for leaving this comment… it made me realize that I had forgotten to include that code snippit in the post! You just need to add cpuScore++ to occur whenever the ball hits the left side of the screen. All fixed now :-)
Awesommmeee tutorial. I made Pong. :D
Can you please show how to add sound??
Good idea, that’s on my to-do list :-)
Very good. Many thanks. A few minor errors (30px ball size vs. 10px) but entirely a fun and rewarding learning experience. I’m going to try to add the sounds and speed up the game as the points add up next. Sooooo… How about Space Invaders next? Or even Pac Man? Very cool, would be that.
How would you make this mobile? I don’t know enough about mobile and probably programming too to make the leap. Aside from obvious screen size changes is there a set of handlers for touching the screen? Depending on how they need to be set up could change everything about the way this game is set up. I would love to see how to do this as well as a start screen and an end game screen based on time or points. Thanks for the great tutorial!
Hi n8studio! Honestly, I don’t have much experience with mobile development either. You already stated that the screen size is smaller, which can be a big limitation. I’m not 100% sure, but I believe most mobile device convert clicks into “touches”, so unless you want to do fancy gestures or multitouch you shouldn’t have too much trouble. One thing I do know for sure is that most mobile devices are much slower than the average computer, so you need to have a simple game, or really optimized code, if you want it to run at a decent speed.
So don’t quote me on this, but I’d say that if you have a simple game with a small screen size, which can be controlled completely by clicking, you will have an easy time exporting it as a mobile application. For anything beyond that, I recommend doing some considerable research before you make the leap.
Publishing for mobile is actually much easier than you’d think (sort of). My limited experience is for android only, so IOS may be different.
To start, you will need android SDK stuff. Also, your phone will have to be in development mode. Once that’s done, it’s simply a matter of optimizing your stage and actors to fit a mobile screen, and publishing for AIR. As you can see in this (incredibly crappy) video, the game works just fine. http://www.youtube.com/watch?v=gvWpE9kjxWI&feature=youtu.be Granted, I made absolutely no effort at all to optimize it, so it doesn’t fit the screen and the ball speed is poorly scaled, but as you can see, the game is perfectly happy living on my phone. I simply copied and pasted all the code and actors into an AIR project and published. Granted, there are some device-esque nuances that would ultimately have to be considered, but as far as this example is concerned, I took the tutorial straight from this page and basically just told it to go be on my phone. Of course, just like any project, there are certainly more details, but the point being, it’s definitely doable, and with only a few minutes’ optimizing, this game could be made to look like it was created especially for mobile. Cheers.
Great work man.. for application programmers like me,it is very precise and point to point. Loved your tutorial. I’m just two days into flash and this game gave me a great exercise. keep going. Expecting little more complicated games from you :)
Great to hear your feedback! I’m definitely planning on making more complicated tutorials in the future, when I have time.
Great tutorial! It really is. The speed is just right and you have a great way of explaining things. It actually makes it enjoyable to read! Thank you :)
You’re welcome!
Great tutorial..this is exactly what I was looking for..Thank you very much
No problem, I’m happy to have helped :-)
Amazing Tutorial, really helps understanding basic actionscript actions too.
I used this tutorial to make this: http://axel230.deviantart.com/art/RD-Flash-Game-301689429 (I made sure to give credit and link back to this page).
If anything, is there a way you could explain how to show a “Winner” or “Loser” text/image when the player or CPU’s score reaches a certain value?
Cool game! I’ll see if I can add the Win/Lose code sometime in the future.
Love your game. Could you share with us how you got the Start, Win, and Lose screens? Thanks.
Thanks for creating this truely amazing tutorial, without it I’d probally have my head stuck in a wall at the moment :P After many hours of searching this is the most straight forward and helpful turtorial I could find. The only problem I have (but its probally just my computer) is that none of the drop menus at the top work for me. Not tutorial related but just though I’d give you a heads up.
Thanks for the heads up. I’ve tested it out on a few different computers/browsers and haven’t had any problems, so I’m assuming it’s just your computer. And on another note, I’m glad to have helped you with your actionscripting!
Thanks dude for your tutorials.. It’s so cool and simple to learn..
Keep posting your tutorials..
Thanks for the comment! I try to get a new tutorial posted about every-other week, so keep checking back :-)
I had to add “updateTextFields();” under “cpuScore++;”, too! Is it missing in the tut?
Thx a lot for this great Tutorial! ;)
Thanks for alerting me to this! Yes, you definitely do need to add that line under “cpuScore++”. I included it in the source code, but apparently I forgot to include it in the online tutorial. I’ll quickly fix that.
Thanks again :-)
Ben,
Great job on the tutorial. My students and I really liked it. I do have a few questions for you though. We are wondering if there was a way to change the paddle color or size based on a score? If possible, can you post instructions or a link to a tutorial that teaches us how to update color and/or size based on the score?
Thanks again and great job!
Mr. B
Hello!
Yes, there definitely are ways to change the size and color of the paddle. I don’t know of any other tutorials on this subject to link to, but here’s a quick guideline on what to do.
— Size:
You can easily adjust the size of the paddles by modifying their “height” properties. Each time someone scores a point, you could update the heights of the paddles accordingly. You’ll have to use your own algorithm to create the effect you want, but for example, this will decrease the height of the player paddle by 5% for each point the player has scored:
var playerPaddleSizeMultiplier:Number = 1 – playerScore * .05;
playerPaddle.height = 50 * playerPaddleSizeMultiplier;
I added this right underneath the playerScore++ line of code, in the main game loop. There are certainly other ways of changing the size, so you and your students can experiment and see what works best.
— Color:
Because we are using a custom MovieClip object, there isn’t an easy property to change the color of an object. (For example, you CAN’T just write playerPaddle.color = “red”.) However, you can work around this by using one of MovieClips’ strengths: frames. If you edit your playerPaddle object on the stage by double-clicking it, you can insert additional frames. Just change the color of the paddle graphics on each frame. Then, make sure to add “playerPaddle.stop()” in your init() function in the program, to make sure the paddle doesn’t start automatically animating. Now, in the same place where I added the code to resize the paddle, just add:
playerPaddle.gotoAndStop(playerScore+1);
This way, your playerPaddle will automatically switch to whatever frame whose number matches up with the player’s current score. The graphics drawn on frame 1 will appear when the player has 0 points, and it will switch to the next frame when the player has 1 point, etc.
If you were so inclined, you could actually skip the code for resizing the paddle, and just draw smaller paddles on each frame. It’s really up to you and your students.
Hopefully this has all helped. Good luck to you guys!
Ben,
Thanks SO MUCH for your reply and this great tutorial. My students and I were able to change color based on your instructions, but we are having trouble with changing the size using “code”. We can change size using the frames method you suggested, but we really want to figure the code part out too.
This is the code we entered –
} else if(ball.x >= stage.stageWidth-ball.width/2){ //check to see if the x position of it’s right side is greater than or equal to the right side of the screen, which would be 550
ball.x = stage.stageWidth-ball.width/2; //and set the x position to that, in case it already moved too far of the right side of the screen
ballSpeedX *= -1; //multiply the x speed by -1 so that the ball is now moving left
playerScore++; //increase playerScore by 1
var playerPaddleSizeMultiplier:Number = 1 – playerScore * .05;
playerPaddle.height = 50 * playerPaddleSizeMultiplier;
playerPaddle.gotoAndStop(playerScore+1);
updateTextFields();
}
When we test the movie Flash give us the following two errors.
Scene 1, Layer ‘Layer 1’, Frame 1, Line 83 1086: Syntax error: expecting semicolon before playerScore.
Scene 1, Layer ‘Layer 1’, Frame 1, Line 83 1093: Syntax error.
Any suggestions?
Thanks,
Todd
I’m 99% sure figured out your problem. The actual code I gave you is fine, however, there was a problem when copying and pasting it into the comment here on the website.
On the line where you declare the new variable (var playerPaddleSizeMultiplier …), there is a minus sign between the “1” and the “playerScore”. When I pasted it into the comment, the site automatically reformatted it as a “dash”. It looks very similar to a minus sign, but the actionscript compiler doesn’t know what it means, so it threw a “syntax error”.
Try fixing that, and you should be good to go.
Let me know if you run into any more problems. :-)
Is there a way to make a pause button????
Yes, and here’s a brief outline of how to do so.
1) Draw a pause button on the stage. Convert it to a Button symbol (or a MovieClip, it doesn’t matter too much). Give it an instance name, such as “pauseButton”.
2) Declare a new “gamePaused” variable: var gamePaused:Boolean = false
3) Create a giant conditional (the “if” statement) inside your main game loop:
if(gamePaused == false) {
//put all of the code currently in your main game loop in here
}
This way, your game will only loop if the game isn’t paused.
4) In your init() function, add a new eventListener:
pauseButton.addEventListener(MouseEvent.CLICK, pauseButtonClicked);
5) Create the pauseButtonClicked function:
function pauseButtonClicked(e:MouseEvent):void {
if (gamePaused == false) {
gamePaused = true;
} else if(gamePaused == true) {
gamePaused = false;
}
This will switch the state of the gamePaused variable whenever you click the button. And by extension, this will pause or un-pause the entire main game loop.
Let me know how it goes, and if you need any additional help!
Ben
I put all the code in where you told me to, however it just deletes everything except for the paddles on the screen when I try to run the program.
Do you get any specific error messages? I’m sorry, but without more details I can’t really figure out what’s going on — I’m fairly certain that the code I gave should work as expected. Try working with it a little to see if you can fix it on your own. If you’re still stuck, let me know and I’ll see what I can do. I can send you source code from my own project if you need it, although you’ll need Flash CS5 or higher to open it.
The error code that it is saying is: “Scene 1, Layer ‘Layer 1’, Frame 1 1084: Syntax error: expecting rightbrace before end of program.”
What does that mean?
This error message means that we are missing one of the right braces (the “}” symbol), which essentially means that we never closed off one of our sections of code properly. Make sure that there are the same number of left braces and right braces in your program, or else it will crash.
This time, it was actually my fault. I forgot to include the final right brace at the end of the pauseButtonClicked function. Add that, and your problem should be fixed.
Sorry about that :-)
Ben,
Thanks again for ALL OF YOU HELP and for this GREAT tutorial. My students and are are leaning a lot about technical writing, communication, online communities, Flash, and AS3 so THANK YOU VERY MUCH!
I’ve worked through your response to LyyrDaremoh’s request and I’m running into a similar problem. I’m not positive, but I believe the error is a result of us not completely understanding “part 3”, the “Giant conditional”. Below is the code I’ve entered based on my understanding of your instructions. The error Flash outputs is –
“Scene 1, Layer ‘Layer 1’, Frame 1 1084: Syntax error: expecting rightbrace before end of program.”
I’m sure we are missing something simple, but we are having a difficult time finding it. Thanks again for your help and have a great day!
Todd
var ballSpeedX:int = -3;
var ballSpeedY:int = -2;
var cpuPaddleSpeed:int = 3;
var playerScore:int = 0;
var cpuScore:int = 0;
var gamePaused:Boolean = false;
init();
function init():void
{
pauseButton.addEventListener(MouseEvent.CLICK, pauseButtonClicked);
stage.addEventListener(Event.ENTER_FRAME, loop);
}
function calculateBallAngle(paddleY:Number, ballY:Number):Number
{
var ySpeed:Number = 5 * ( (ballY-paddleY) / 25 );
trace(ySpeed);
return ySpeed;
}
function pauseButtonClicked(e:MouseEvent):void {
if (gamePaused == false) {
gamePaused = true;
} else if(gamePaused == true) {
gamePaused = false;
}
function updateTextFields():void
{
playerScoreText.text = (“Player Score: ” + playerScore);
cpuScoreText.text = (“CPU Score: ” + cpuScore);
}
function loop(e:Event):void
{
if(gamePaused == false) {
if( playerPaddle.hitTestObject(ball) == true ){
if(ballSpeedX 0){
ballSpeedX *= -1;
ballSpeedY = calculateBallAngle(cpuPaddle.y, ball.y);
}
}
if(cpuPaddle.y ball.y + 10){
cpuPaddle.y -= cpuPaddleSpeed;
}
playerPaddle.y = mouseY;
//check if top of paddle is above top of screen
if(playerPaddle.y – playerPaddle.height/2 stage.stageHeight){
playerPaddle.y = stage.stageHeight – playerPaddle.height/2;
}
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 = stage.stageWidth-ball.width/2){ //check to see if the x position of it’s right side is greater than or equal to the right side of the screen, which would be 550
ball.x = stage.stageWidth-ball.width/2; //and set the x position to that, in case it already moved too far of the right side of the screen
ballSpeedX *= -1; //multiply the x speed by -1 so that the ball is now moving left
playerScore++; //increase playerScore by 1
var playerPaddleSizeMultiplier:Number = 1 -playerScore * .20;
playerPaddle.height = 50 * playerPaddleSizeMultiplier;
playerPaddle.gotoAndStop(playerScore+1);
updateTextFields();
}
//now we do the same with the top and bottom of the screen
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 speec so that it is moving up now
}
}
}
Thanks for showing me the source code. I figured it out again… and this time it was definitely my fault :P
I forgot to include an extra right brace (The “}” symbol) to close off my “pauseButtonClicked” function. I could tell what the general error was because of the error message “expecting right brace before end of program.” If you ever see this, go back through your code and make sure that the number of left braces is matched with the same number of right braces. It’s easy to forget to include one of them, and it will crash your entire code.
Add the final right brace to the pauseButtonClicked function and you should be OK.
Let me know if this fixes it for you.
I have put in the code as it has said and now the game wont move. What have I done wrong?
Make sure you finish the pauseButtonClicked function by adding another right brace (the “}” symbol).
In my comment, I forgot to include the final right brace for that function. Sorry! Let me know if this fixes it for you. :-)
I keep getting this message in my output;
TypeError: Error #2007: Parameter listener must be non-null.
at flash.events::EventDispatcher/addEventListener()
at pong_fla::MainTimeline/init()
at pong_fla::MainTimeline/frame1()
Do you understand how to get it so this stops showing? It’d be really helpful. :))
Ben,
It worked! Thanks again. My students and I really appreciate all of your help.
I’ve been unable to open any of the sample .fla files you have posted. I have CS3. Each time I get an “unexpected file format” error message. Is that because I have an old version?
Unfortunately, yes :(
I created all of the Pong tutorials in CS4, which can’t be opened by CS3 unless you explicitly export the Flash files as a CS3 document. I should have remembered to do that when I was creating the tutorials, but I wasn’t thinking.
Now, I am using Flash CS6. And as a scheme to force users to upgrade their version of Flash, Adobe only lets CS6 export back to CS5 documents. So it’s too late now for me to update the files for CS3 :(
Solutions: If you can find anyone with CS4 who would volunteer to open the file for you, and export it as a CS3 document, it should open for you.
Otherwise, if you are only looking for the code, just let me know and I can upload a PDF version of the full source code.
Let me know how I can help.
Ben
Maybe you could also add a tutorial on how to add sounds to the game, like a sound when the ball hits the walls and the paddles and a sound when someone scores. And maybe some background music?
Also, when you make a title screen tutorial maybe add the possibility of a multiplayer gamemode where one player controls a paddle with the mouse and the other player controls the other paddle with the arrow keys?
Anyways I really enjoyed this tutorial, can’t wait to start with the other tutorials.
You really know how to explain things to people. Not everyone can do that.
Thanks so much. All of your suggestions are great ideas, and are tutorials which have been requested by at least few individuals. I’ll see how quickly I can get to them (adding sound, the title screen, and keyboard controls).
Hey Ben,
I’m one of Mr. Benrud’s students (who commented earlier) I wanted to advise you on the comments you made concerning the code that changes the size of the paddle. Up to this point you’re tutorial has been consistent and educational, and I thank you for taking your time to help the masses with the basics of flash. Now about the code, you tell us to
“var playerPaddleSizeMultiplier:Number = 1 – playerScore * .05;
playerPaddle.height = 50 * playerPaddleSizeMultiplier;
I added this right underneath the playerScore++ line of code, in the main game loop.”
I did this and it seems flash doesn’t like the form of math you used to calculate 1 – playerScore * .05;
I received the following compiled errors.
Scene 1, Layer ‘Layer 1’, Frame 1, Line 66 1093: Syntax error.
Scene 1, Layer ‘Layer 1’, Frame 1, Line 66 1086: Syntax error: expecting semicolon before playerScore.
Scene 1, Layer ‘Layer 1’, Frame 1, Line 76 1093: Syntax error.
Scene 1, Layer ‘Layer 1’, Frame 1, Line 76 1086: Syntax error: expecting semicolon before playerScore.
Any help would be much appreciated,
Thank you!
Hey Martin,
I realized that the problem is merely a typo. Look at the minus sign between the “1” and the “playerScore”. Well, it isn’t actually a minus sign — it’s a dash, which my website automatically reformatted when I pasted the code into the comment. Delete it, and replace it with a proper minus sign.
That should be all you need to get it working. Good luck!
So, i’ve been trying to edit the script so that the difficulty gradually increases the higher the playerscore score gets. So I changed ballSpeedX and cpuPaddleSpeed into:
var cpuPaddleSpeed:int = 3 + playerScore
var ballSpeedX:int = 5 + playerScore
But it doesn’t seem to work.
It seems like the playerScore stays at 0 and only the “Player Score: 0” text changes.
Have you got any ideas on how to fix this?
I think I might know your problem. Even though you are declaring your cpuPaddleSpeed to be equal to 3+playerScore in the beginning, that only sets its initial value. In other words, because the playerScore is only 0 when you declare this variable, your cpuPaddleSpeed is created with a value of 3. And unless you write some some later on to update the speed, it will never change.
So what you want to do, is right underneath the code where you increase the player’s score (“playerScore++”), you want to add a line of code saying “cpuPaddleSpeed = 3 + playerScore;”.
You’ll want to do the same thing with the ballSpeedX variable.
Remember, declaring a variable only sets its initial value. It won’t automatically update on its own.
Hopefully this will fix your problem. Let me know how things work out.
Thank you so much! It’s working now and I understand what went wrong.
Ben,
Thanks again for the tutorial! It’s amazing.
I am playing around with one of the questions Todd Benrud asked, and was wondering if it would be possible to change the entire stage instead of just one object.
For example I modified:
playerPaddle.gotoAndStop(playerScore+1);
to
playerPaddle.gotoAndStop(lifePoints-5);
so when all of the life points I have created are gone, the playerPaddle changes, but I was wondering if I would be able to define the stage? Thanks for all your help, sorry if I’m not clear enough.
whenever I play this, the ball is stuck on the right side, only moving up and down, and the playerScore keeps blinking… can you tell me what’s wrong? Here’s my code, what I think is the same as yours…
var cpuPaddleSpeed:int = 3;
var ballSpeedX:int = -3;
var ballSpeedY:int = -2;
var playerScore:int = 0;
var cpuScore:int = 0;
init();
function updateTextFields():void
{
playerScoreText.text = (“Player Score: ” + playerScore);
cpuScoreText.text = (“Computer Score: ” + cpuScore);
}
function init():void
{
stage.addEventListener(Event.ENTER_FRAME, loop);
}
function calculateBallAngle(paddleY:Number, ballY:Number):Number
{
var ySpeed:Number = 5 * ( (ballY-paddleY) / 25 );
// (ballY-paddleY) / 25 will be between -1 and 1 depending on where the ball hits
return ySpeed;
}
function loop(e:Event):void
{
if( playerPaddle.hitTestObject(ball) == true){
if(ballSpeedX 0){
ballSpeedX *= -1;
ballSpeedY = calculateBallAngle(cpuPaddle.y, ball.y); //add this
}
}
if(cpuPaddle.y ball.y + 10){
cpuPaddle.y -= cpuPaddleSpeed;
}
playerPaddle.y = mouseY;
//check if top of paddle is above top of screen
if(playerPaddle.y – playerPaddle.height/2 stage.stageHeight){
playerPaddle.y = stage.stageHeight – playerPaddle.height/2;
}
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 = stage.stageWidth-ball.width/2){ //check to see if the x position of it’s right side is greater than or equal to the right side of the screen, which would be 550
ball.x = stage.stageWidth-ball.width/2; //and set the x position to that, in case it already moved too far of the right side of the screen
ballSpeedX *= -1; //multiply the x speed by -1 so that the ball is now moving left
playerScore++; //increase playerScore by 1
}
//now we do the same with the top and bottom of the screen
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 speec so that it is moving up now
}
if(ball.x = stage.stageWidth-ball.width/2){
ball.x = stage.stageWidth-ball.width/2;
ballSpeedX *= -1;
playerScore++; //increase playerScore by 1
updateTextFields();
}
}
nevermind, i changed it up a little, this time, it works, except the number score disappears after getting a point. here’s the new code:
var cpuPaddleSpeed:int = 3;
var ballSpeedX:int = -3;
var ballSpeedY:int = -2;
var playerScore:int = 0;
var cpuScore:int = 0;
init();
function updateTextFields():void
{
playerScoreText.text = (“Player Score: ” + playerScore);
cpuScoreText.text = (“Computer Score: ” + cpuScore);
}
function init():void
{
stage.addEventListener(Event.ENTER_FRAME, loop);
}
function calculateBallAngle(paddleY:Number, ballY:Number):Number
{
var ySpeed:Number = 5 * ( (ballY-paddleY) / 25 );
// (ballY-paddleY) / 25 will be between -1 and 1 depending on where the ball hits
return ySpeed;
}
function loop(e:Event):void
{
if( playerPaddle.hitTestObject(ball) == true){
if(ballSpeedX 0){
ballSpeedX *= -1;
ballSpeedY = calculateBallAngle(cpuPaddle.y, ball.y); //add this
}
}
if(cpuPaddle.y ball.y + 10){
cpuPaddle.y -= cpuPaddleSpeed;
}
playerPaddle.y = mouseY;
//check if top of paddle is above top of screen
if(playerPaddle.y – playerPaddle.height/2 stage.stageHeight){
playerPaddle.y = stage.stageHeight – playerPaddle.height/2;
}
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 = stage.stageWidth-ball.width/2){ //check to see if the x position of it’s right side is greater than or equal to the right side of the screen, which would be 550
ball.x = stage.stageWidth-ball.width/2; //and set the x position to that, in case it already moved too far of the right side of the screen
ballSpeedX *= -1; //multiply the x speed by -1 so that the ball is now moving left
playerScore++; //increase playerScore by 1
if(playerScoreText.text = (“Player Score: ” + playerScore)){
updateTextFields();
}
}
//now we do the same with the top and bottom of the screen
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 speec so that it is moving up now
}
}
Hi. I’ve been trying again and again and looking up on the comments said here, but I cannot fix in any way the scoring system. I tried lot of stuff, some moves the number to another side etc.
Every time one side scored the score automatically disappears even if I embedded it change colors etc.
This is my first time ever to try this and I’m lost at the scoring system. Please help…
1) Click on one of the text boxes
2) Go to propterties
3) Change the ‘Text Engine” from Classic Text to TLF Text
4) Rerun – if this works then do the same to the other text box
Help?
Absolutely brilliant tutorial. I have looked at several and this one is by far the best!
Thanks heaps for this.
Thanks, I’m glad to help!
Amazing tutorial, want to see more from this series!
Loved the tutorial, thanks a lot and congratulations on your form of explaining the code, it’s really good, Ben!
I added the repositioning of the ball after someone scores and a winning screen. looks boss!
Would be sweet to have sounds.
Thanks! I’m glad you like it. I’d love to do a tutorial on adding sound — maybe if I have some free time soon I’ll try to make another tutorial. :-)
Can we fix a score limit to our game…so that after certain points Game gets over..and the one who score more gets win…
Yes, and that’s a great idea for part 7, if I ever get around to writing it… :)
Hello Ben,
I have noticed you writing a few replies on when you will be getting to adding the “Winner/Loser” page and I also would love to know the code for this, I feel like the code wouldn’t be to much so if you could somehow skim it down enough for you to explain in a reply that would be fantastic.
Anyway thank you so much for this Tutorial I have added so much and all that is left is the “Winner/Loser” page. Again thank you.
Great tutorial. It’s well-written and deliberate, which is exactly what someone learning needs. Assuming the reader has prior knowledge of the subject has been the downfall of many otherwise great tutorials.
Just for fun, I enclosed the AI in an if statement that reads “if(ball.x>(stage.stageWidth/3)){ }” This completely stops the movement of the CPU paddle when the ball is on the left 1/3rd of the screen. The idea was to make life a little harder for the CPU and also to include what appears to be intermittent pauses in movement, as if the CPU is having to stop and “think” about what it wants to do next. Not important, I guess, but I thought it was fun.
Thanks again for the tutorial.
Cheers
Thanks, and great idea about the “if(ball.x>(stage.stageWidth/3)){ }” — cool to see how such a simple game as pong can be easily modified to produce different difficulties/effects.
Finally a good AS3 resource. Thanks alot!
Thanks, and no problem! :-)
Love these tutorials, but I am getting an odd error that I can’t seem to figure out.
Line 19 1119: Access of possibly undefined property text through a reference with static type int.
Basic google searches aren’t giving me an answer, and all I did was copy in your code, so I have no ideawhat could have went wrong. I am using AS3 in CS6.
Nevemind, I figured out the issue and now this works great, I have a few new mechanics im going to try adding. Thanks so much for providing such a solid base on which to get started!
I am wondering one more thing- is there any way I can ‘clean up’ the code- some way to make it more concise and/or organized, like maybe having different windows for different functions?
try one thing that i ussualy do: i place variables and function that to same thing together and above i wrote: // “what this does” so it looks like:
// ball moving <—- this wont effect ur code, try it and u'll see
var….
funtion ballMoving()…
// update score
var….
i hop it helps and u will understand, coz i don't know how to explain this in english
the score wont work even if i embed it or put a white box behind it.
Thx so so so so so MUCH!! I really needed this – it’s perfect! :-D
Great tutorial – easy to understand. You saved my day :-)
Quick Fix: On mousewheel scroll on the score text, it resets to blank.
I cannot get the score to go up higher than 2. Also whenever the player scores then the cpu scores the player score goes back to zero.
I would love a title screen and winning / losing
I would love a title and ending screen, thanks for the awesome tutorial though
Thanks!