Now that you have made the connections, close Interface Builder and return to XCode. We need to set up some constants. You can hardcode these values in somewhere, but making them constants makes them easier to change when you are tweaking the mechanics of your game. Open up iTennisViewController.m and add the following code.
Let me explain the purpose of the constants. The first 2 are game states. We use these to determine what is to be shown on screen. Is the game paused, is it running, is it at the title screen? We will add more states later on in the game. The next 2 variables are speeds for the ball to travel. Since the game is 2D, the ball can have an X and Y speed to make up its velocity vector. The next line synthesizes the variables we will use to create their getter and setter methods automatically.
Now let’s write the viewDidLoad method. Add the following code:
First, we are setting our game state to a paused game state. This is so the game doesn’t start right away when the view loads. Next, we create a vector for the ball’s velocity. Adjust the constants that we defined earlier for a faster or slower ball speed. Finally, we create an NSTimer instance. The first parameter is the timestep. We have set the time step to 0.05 seconds. Adjusting this will change the speed of the entire game. Next we set the target. This is telling the timer where the callback is located. The callback is the next parameter. Basically, we are telling the timer to call self.gameLoop every 0.05 seconds. We don’t need to worry about the userInfo param. The last parameter just tells the timer to repeat.
Now that we have initialized our game, let’s create the game loop. Add the following method:
First, we are checking to see if the game is in a running state (we don’t want to move the ball in a paused state). If the game is not running, we will show the tapToBegin label. This is just the label defined earlier that tells the user to tap the screen to begin.
If the game is running, we start by moving the ball according to its velocity vector. The next few lines do some bounds checking. If the ball hits the side of the screen, we want to reverse its velocity so that it “bounces”. Without this code, the ball would fly off the screen.
The last bit of code we will need to write is the touchesBegan method. We will use this method to start the game when the game is in a paused state. Add the following code:
What this does is first checks to see if we are in a paused state. If so, we hide the tapToBegin label and set the game in a running state. This will get the game running. Eventually, we will write the code to control the player paddle in this function.
Finally, being good iPhone developers, we need to clean up the resources that we allocated. Add the following code to the dealloc method.
That concludes part 1 of our game development tutorial series. If you have any questions or comments, feel free to leave them in the comments section of this post. You can download the source code here. Happy iCoding!
Thanks for the reply Naren.. I have checked all these things, and they are ok. In fact, it builds fine. the problem is in the launch. I am going to go through this entire blog from the beginning and then go back to this example. perhaps then I will have some insight.
is this done half way? It dont seem to be finished because mine crashes every time in the launch stage. I am 100% sure the code is perfect I’ve checked and rechecked this all seems fine but the launch crashes every time …
hmmm well I reworked the code and I got it going but I dont have any movement in the paddles and the ball is going everywhere . Thanks for your replies.
one thing i wanted to tell you that in gameLoop there is some code that is missing . it is not my fault. i pasted the whole code but the page is not showing that part. if i will paste again there will be the same problem. this is not my page so i cant even upload. I have completed this game almost. but left some thing to make it final. and i dont even have any way to tell it to others. Brandon is also not replying.
THANKS!!! My final project for my undergrad is a iPhone game your tutorial saved me so much time and a lot of headache. You are very clear and your directions are great. If you haven’t written a book you should consider it.
Actually if you have just copy and pasted the code of game loop then this problem will happen , because he might have pasted the correct code but because of some reasons some thing is missing. like first condition where we are directing the ball from walls that whole if condition is wrong. i also tried to paste my code but i saw that two if conditions are merged together and one wrong condition is made and that was effecting our application. wait let me help you.
in gameloop…
maintain the code written by brandon…
and then copy Joe’s part from
CGRect raquet_rect = CGRectMake(raquet_yellow.center.x, raquet_yellow.center.y, 100, 20);
the first two if conditions of brandon’s should not be changed.other than that see what joe has pasted .
hope it will work.
At first, I also got this error when building and running
*** Terminating app due to uncaught exception
For me it was a spelling error in this part:
[NSTimer scheduledTimerWithTimeInterval:0.05 .. etc.
Seems to me that the compiler doesn’t really check this kind of messaging, which can easily cause errors.
I have a question though about the touchesBegan method.. do you really have to type in that entire syntax? Are you supposed to know this as a programmer? I mean, shouldn’t xcode generate a stub for it somehow? Or maybe this is because I made the view to the file’s owner connection only AFTER I started writing code?
I’m adding the Reference Outlets to the racquets and ball. THe two racquets and the ball go fine, but when I go to drag the Reference Outlet line for the scores over to File’s Owner, all I see is “view” no player_score or computer_score. What did I miss?
P.S.
If I select a racquet and add a Reference point, I see player_score and computer score.
Great site and awesome tutorial! I’m having only one issue – once the ball starts downward in motion it redirects before it goes all the way down to the bottom. I’ve tried a number of various things trying to pinpoint where the issue is… I’ve checked my code versus yours and it’s the same, I’m thinking it’s something I’m doing wrong with interface builder. Does anyone have any ideas?
Sry I think I dont understand you right(I think ist my false), because it dosent work. I woukd be greate if you could have a look at my gameloop:
-(void)gameLoop
{
if(gameState == kGameStateRunning) {
Hi all guys,
Might you will find something helpful and new in this post.
I wanted to share some things to you. I will try to make it clear to you.
first problem is collision detection. how to check whether two images are colliding or not. there are two methods
CGRectContainsRect and CGRectContainsPoint, but try to use this one CGRectInersectsRect([ball frame],[racquet_yellow frame] == 1). It will work exactly and properly.
second thing is how to manage the ball diversion with the balls, you need not to put two if condition like that.
do it like
after first line of game loop
put
if(CGContainsRect ([self.view frame], [ball frame]))
{
// your all necessary code which should work when ball is inside the boundaries
}
else
{
//try putting the conditions here to divert the ball
}
third is how to divert the ball when collides with the racquet or other ball.
you use cgintersectsrect function when ever it is true inside that.
ballVelocity = CGPointMake(ball.center.x – racquet_yellow.center.x , ball.center.y – racquet_yellow.y);
it will divert the ball automatically depending on where the ball strikes.
hope it is clear to you. this is all the logic, use your skills to match it.
Thanks
ok ok .. I am writing the function here, you people take care of the caps or small , i m not copying and pasting I am directly writing here. so might be some spelling mistakes.
i did not check with the gameState , you manage yourself , but this code should be inside where gameState == kGameStateRunning.
hope you all got it. try to make it work.
Thanks a lot.
Hey not again a lot of code is missing, what is happening . i dont understand again i m trying… to paste
this is the code followed by this line replace with this code…i dont want that you people try with the missing code and face problems .. sorry for increasing the page length Brandon…
if( ball.center.y + ballRadius >= 460 || ball.center.y – ballRadius <= 0)
{
ballVelocity.y = -ballVelocity.y ;
}
}
}
this all code is under gameState = running condition.
again Brandon sorry for the long post and using your page.
Hello everyone. I am completely new to xcode and am in need of some help. I keep getting the following errors in:
iTennisViewController.m
iTennisAppDelegate.m
error:property ‘gameState’ with ‘retain’ attribute must be of object type.
error:property ‘ballVelocity’ with ‘retain’ attribute must be of object type.
What did I do wrong? I’m not even going to attempt a rational thought here because it will only show my complete noob-ness. Thanks!
I’m really glad some decent guides are finally popping up lately! I remember when I was trying to get my first game started, no Objective C knowledge, never developed on a Mac before, and with great ambitions; I found myself perplexed with the lack of decent information out there. This was when Apple still had the NDA up.
So, I decided that when my game finished, I’d make it open source, such that *everyone* would benefit from it.
Gorillas () is now in the App Store, and a second update is coming out soon. And all the while, the entire development process and source code can be found and followed at:
So, I invite everyone to check it out if they’re wondering how a fully featured OpenGL/ES game looks like in source. Any questions about it you can always direct my way (contact info on the website).
Can someone please send me the movie file or post it on a file host? The country I am in blocks this website and while I can access it through a proxy server, I can’t access the video
thanks for explaining in such an easy detailed manner that a beginner like myself can understand – you give great examples and i look forward to more!! thank you.
I followed the instructions listed above and copied the code (as best as I can) into my project. However, I run into errors when I click on the “Build and Go” button.
Can I ask one of the experts here for their help? I’m certain that I’m missing something fairly basic, but I am very new to the iphone SDK.
I have posted screenshots of the error on my page:
Thanks in advance!
Hau
P.S. Brandon, what program did you use to record your tutorial? I would like to create a few tutorials for my area of work as well. Thanks!
Hey, I’m having what is probably a very simple problem…when I select new referencing outlet for any of the paddle images, and drag it to file’s owner, the menu of image names that opens in the video opens, but instead of a list of names, it just says ‘view’. I’ve checked the code and it seems to be in order, but seeing as this is my first time with xcode, I’m most likely missing something obvious.
This might not be related, but when I was entering the IBOutlets, the code was not turning blue, as it was in the picture above…
I was able to make the app show up after following the tutorial but only saw the background image (the tennis court), all other added views were missing. I guess I missed something but couldn’t find out where. Any advice would be highly appreciated.
best tutorial i have ever found on internet !!
Thanks a lot !! really supperb for starter…..
with a very simple and much easier language….
please teach us more complex game…
219 Comments
Thanks for the reply Naren.. I have checked all these things, and they are ok. In fact, it builds fine. the problem is in the launch. I am going to go through this entire blog from the beginning and then go back to this example. perhaps then I will have some insight.
is this done half way? It dont seem to be finished because mine crashes every time in the launch stage. I am 100% sure the code is perfect I’ve checked and rechecked this all seems fine but the launch crashes every time …
hmmm well I reworked the code and I got it going but I dont have any movement in the paddles and the ball is going everywhere . Thanks for your replies.
hey Naren…
can you upload the project so we can download it with your changes?
@techy
one thing i wanted to tell you that in gameLoop there is some code that is missing . it is not my fault. i pasted the whole code but the page is not showing that part. if i will paste again there will be the same problem. this is not my page so i cant even upload. I have completed this game almost. but left some thing to make it final. and i dont even have any way to tell it to others. Brandon is also not replying.
ok thanks for replying =D
Is there a way to create the ball and paddles the old fashioned way with code and WITHOUT Interface Builder?
You are the MAN! If only Apple had guys like you writing their tutorials for them…
THANKS!!! My final project for my undergrad is a iPhone game your tutorial saved me so much time and a lot of headache. You are very clear and your directions are great. If you haven’t written a book you should consider it.
@Joe
If I use your code, the ball does just collesise with the paddel at the right end and not with the hole paddel. Could you help me??
Thanks a lot… hope you continue this soon.
@Jo,
Actually if you have just copy and pasted the code of game loop then this problem will happen , because he might have pasted the correct code but because of some reasons some thing is missing. like first condition where we are directing the ball from walls that whole if condition is wrong. i also tried to paste my code but i saw that two if conditions are merged together and one wrong condition is made and that was effecting our application. wait let me help you.
in gameloop…
maintain the code written by brandon…
and then copy Joe’s part from
CGRect raquet_rect = CGRectMake(raquet_yellow.center.x, raquet_yellow.center.y, 100, 20);
the first two if conditions of brandon’s should not be changed.other than that see what joe has pasted .
hope it will work.
Brilliant! However, when I ran it just to see what would happen I got 2 warnings and 24 build errors!
Thanx a Million, to Brandon, Naren and Joe. You guys have done a great job putting this together for us NOOBs. Much appreciated.
Thanks for the great tutorial.
At first, I also got this error when building and running
*** Terminating app due to uncaught exception
For me it was a spelling error in this part:
[NSTimer scheduledTimerWithTimeInterval:0.05 .. etc.
Seems to me that the compiler doesn’t really check this kind of messaging, which can easily cause errors.
I have a question though about the touchesBegan method.. do you really have to type in that entire syntax? Are you supposed to know this as a programmer? I mean, shouldn’t xcode generate a stub for it somehow? Or maybe this is because I made the view to the file’s owner connection only AFTER I started writing code?
Hey,
I’m adding the Reference Outlets to the racquets and ball. THe two racquets and the ball go fine, but when I go to drag the Reference Outlet line for the scores over to File’s Owner, all I see is “view” no player_score or computer_score. What did I miss?
P.S.
If I select a racquet and add a Reference point, I see player_score and computer score.
What gives?
Thanks
Ricky
Brandon,
Great site and awesome tutorial! I’m having only one issue – once the ball starts downward in motion it redirects before it goes all the way down to the bottom. I’ve tried a number of various things trying to pinpoint where the issue is… I’ve checked my code versus yours and it’s the same, I’m thinking it’s something I’m doing wrong with interface builder. Does anyone have any ideas?
Thanks,
Kyle
@Ricky
Check to make sure you declared your two score labels as “IBOutlet UILabel” and not UIImageView like the ones before them
@Kyle,
Well, I checked and it was ImageView, changed it to UILabel and it still doesn’t work. I guess I’m getting close. ANy more ideas? THanks
Did a relaunch, it asked me to save, and presto! Thanks Kyle and good luck with the ball bouncing too soon. Any idea when Part 2 will be up? Thanks
@Ricky
Don’t forget to take care of them below for the @property portion
@Ricky
Glad it worked – yeah I have no idea what’s wrong on my end
Thanks. Just redid the @property. Why do I need IBOutlet AND @property? Sorry, I know nothing about programming, really want to learn though. Thanks.
Oh, BTW, have you finished your app up to actually playing it? Or are we still waiting on Part 2? I’m curious when it will be out.
urgh – had a width mixed with a height. It’s working now.
Looking forward to part two!
@Naren
Sry I think I dont understand you right(I think ist my false), because it dosent work. I woukd be greate if you could have a look at my gameloop:
-(void)gameLoop
{
if(gameState == kGameStateRunning) {
ball.center = CGPointMake(ball.center.x + ballVelocity.x , ball.center.y + ballVelocity.y);
if(ball.center.x > self.view.bounds.size.width || ball.center.x self.view.bounds.size.height || ball.center.y < 0) {
ballVelocity.y = -ballVelocity.y;
}
CGRect raquet_rect = CGRectMake(racquet_yellow.center.x, racquet_yellow.center.y, 100, 20);
if(CGRectContainsPoint(raquet_rect, ball.center)) {
ballVelocity.y = -ballVelocity.y;
ballVelocity.x = -ballVelocity.x;
}
} else {
if(tapToBegin.hidden) {
tapToBegin.hidden = NO;
}
}
}
thanks for your help anyway
Hi all guys,
Might you will find something helpful and new in this post.
I wanted to share some things to you. I will try to make it clear to you.
first problem is collision detection. how to check whether two images are colliding or not. there are two methods
CGRectContainsRect and CGRectContainsPoint, but try to use this one CGRectInersectsRect([ball frame],[racquet_yellow frame] == 1). It will work exactly and properly.
second thing is how to manage the ball diversion with the balls, you need not to put two if condition like that.
do it like
after first line of game loop
put
if(CGContainsRect ([self.view frame], [ball frame]))
{
// your all necessary code which should work when ball is inside the boundaries
}
else
{
//try putting the conditions here to divert the ball
}
third is how to divert the ball when collides with the racquet or other ball.
you use cgintersectsrect function when ever it is true inside that.
ballVelocity = CGPointMake(ball.center.x – racquet_yellow.center.x , ball.center.y – racquet_yellow.y);
it will divert the ball automatically depending on where the ball strikes.
hope it is clear to you. this is all the logic, use your skills to match it.
Thanks
ok ok .. I am writing the function here, you people take care of the caps or small , i m not copying and pasting I am directly writing here. so might be some spelling mistakes.
-(void)gameloop
{
ball.center.x = CGPointMake(ball.center.x + ballVelocity.x , ball.center.y + ballVelocity.y)
if(CGRectContainsRect([self.view frame],[ball frame]))
{
//ball collision to yellow racquet collision
if(CGRectIntersectsRect([ball frame],[racquet_yellow frame])==1)
{
ballVelocity = CGPointMake(ball.center.x – racquet_yellow.center.x , ball.center.y – racquet_yellow.center.y);
}
// ball to racquet_green collision detection
if(CGRectIntersectsRect([ball frame],[racquet_green frame])==1)
{
ballVelocity = CGPointMake(ball.center.x – racquet_green.center.x , ball.center.y – racquet_green.center.y);
}
// code to move the computer racquet automatically
if(ball.center.x = 320 || ball.center.x – ballRadius = 460 || ball.center.y – ballRadius <= 0)
{
ballVelocity.y = -ballVelocity.y ;
}
}
}
i did not check with the gameState , you manage yourself , but this code should be inside where gameState == kGameStateRunning.
hope you all got it. try to make it work.
Thanks a lot.
Hey not again a lot of code is missing, what is happening . i dont understand again i m trying… to paste
this is the code followed by this line replace with this code…i dont want that you people try with the missing code and face problems .. sorry for increasing the page length Brandon…
// code to move the computer racquet automatically
if(ball.center.x = 320 || ball.center.x – ballRadius = 460 || ball.center.y – ballRadius <= 0)
{
ballVelocity.y = -ballVelocity.y ;
}
}
}
this time also missing…
hufff … ok i will paste one by one…
// code to move the computer racquet automatically
if(ball.center.x <= self.bound.size.height / 2)
{
//racquet_green’s x only will change not y, y will be the same
racquet_green.center = CGPointMake(ball.center.x , racquet.center.y);
}
}
oh ok now it is here , code continues…..
else
{
if(ball.center.x + ballRadius >= 320 || ball.center.x – ballRadius < 0)
{
ballVelocity.x = -ballVelocity.x;
}
continues…
and it ends with it
if( ball.center.y + ballRadius >= 460 || ball.center.y – ballRadius <= 0)
{
ballVelocity.y = -ballVelocity.y ;
}
}
}
this all code is under gameState = running condition.
again Brandon sorry for the long post and using your page.
I have used one variable ballRadius either use statically 8 for statically, or use
NSInteger ballRadius = ball.bounds.size.width/2;
it will give you the ball’s radius.
ooops,
my posts are deleted .
ok great. I will not post more stuff now onwards.
Thanks a lot.
Hey,
This as been out for a month! When is Part 2 coming out? Thanks Brandon! Great Tutorial thus far
-Ricky
Hello everyone. I am completely new to xcode and am in need of some help. I keep getting the following errors in:
iTennisViewController.m
iTennisAppDelegate.m
error:property ‘gameState’ with ‘retain’ attribute must be of object type.
error:property ‘ballVelocity’ with ‘retain’ attribute must be of object type.
What did I do wrong? I’m not even going to attempt a rational thought here because it will only show my complete noob-ness. Thanks!
nevermind. i just figured it out. i was using a ‘retain’ in the @property
ok, the app starts but crashes due to an error with the NSTimer. It doesn’t detect any errors initially only when simulation starts.
Help would be appreciated.
Hi,
I am new ti iPhone. Working on a small game. I can compile the file the project that you explain but I get an error.
I need help to make this project run.
The error occured in line 14 of main.m: int retVal = UIApplicationMain(argc, argv, nil, nil);
I am able to run your sample, but I need to know what is the above error for my own understanding.
Thanks for help.
Best
Sam
Great tutorial! REALLY looking forward to the next one. Thanks
Thanks for the great tutorial! I can’t wait to try it out. Looking forward to the rest of your series!
Hey!
I’m really glad some decent guides are finally popping up lately! I remember when I was trying to get my first game started, no Objective C knowledge, never developed on a Mac before, and with great ambitions; I found myself perplexed with the lack of decent information out there. This was when Apple still had the NDA up.
So, I decided that when my game finished, I’d make it open source, such that *everyone* would benefit from it.
Gorillas () is now in the App Store, and a second update is coming out soon. And all the while, the entire development process and source code can be found and followed at:
So, I invite everyone to check it out if they’re wondering how a fully featured OpenGL/ES game looks like in source. Any questions about it you can always direct my way (contact info on the website).
Hoping to serve the community,
Lhunath
Can someone please send me the movie file or post it on a file host? The country I am in blocks this website and while I can access it through a proxy server, I can’t access the video
Here’s the direct link to the video: http://icodeblog.com/wp-content/uploads/2009/01/Game_1.mov
Thank you!
thanks for explaining in such an easy detailed manner that a beginner like myself can understand – you give great examples and i look forward to more!! thank you.
Hi Gang,
I am a complete n00b, so please go easy on me.
I followed the instructions listed above and copied the code (as best as I can) into my project. However, I run into errors when I click on the “Build and Go” button.
Can I ask one of the experts here for their help? I’m certain that I’m missing something fairly basic, but I am very new to the iphone SDK.
I have posted screenshots of the error on my page:
Thanks in advance!
Hau
P.S. Brandon, what program did you use to record your tutorial? I would like to create a few tutorials for my area of work as well. Thanks!
Hi Lhunath,
Congratulations on creating the game!
Also, thanks for releasing the source code. I’m sure a lot of the beginners like myself will learn from your example.
Thanks!
Hau
Great guide! When will part 2 & 3 be out?
Hey, I’m having what is probably a very simple problem…when I select new referencing outlet for any of the paddle images, and drag it to file’s owner, the menu of image names that opens in the video opens, but instead of a list of names, it just says ‘view’. I’ve checked the code and it seems to be in order, but seeing as this is my first time with xcode, I’m most likely missing something obvious.
This might not be related, but when I was entering the IBOutlets, the code was not turning blue, as it was in the picture above…
any help would be appreciated! thanks..
This is brilliant. Exactly what a lot of aspiring Mac developers are looking for. Thank you for providing this for us!
I was able to make the app show up after following the tutorial but only saw the background image (the tennis court), all other added views were missing. I guess I missed something but couldn’t find out where. Any advice would be highly appreciated.
Thanks in advance
best tutorial i have ever found on internet !!
Thanks a lot !! really supperb for starter…..
with a very simple and much easier language….
please teach us more complex game…
Thanks a lot again..
39 Trackbacks