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!
any approximate idea how many tutorials you will publish in this series and how long it will take. Just some approximate ideas so that we can buckle up for the ride.
One small suggestion, maybe you can post some small assignment type questions so that we can do play around on our own too .
This is exactly the kind of think I am looking for. I am totally new to Objective-C and the OSX and iPhone Frameworks. (only did windows development before)
I think pong is an excellent “hello world” for writing games as it contains many basics. As you already pointed out however it doesn’t include any animation/sprite type examples. Any chance you could toss in a small animation example? Maybe have the raquets change color or something when they collide with the ball or something simple?
I’m also new to the Mac “world”, your tutorial came in the right moment.
I’m having trouble though, when I run iTennis it crashes and generates a report to send to Apple. Can you help me find out what am I doing wrong? The build shows no errors nor warnings.
Just to give you more information, look what I’ve found on the report it generates to Apple:
*** Terminating app due to uncaught exception ‘NSInternalInconsistencyException’, reason: ‘-[UIViewController _loadViewFromNibNamed:bundle:] loaded the “iTennisViewController” nib but the view outlet was not set.’
Great tutorial as always. I’m looking forward to seeing more of the obscure aspects of game programming as well. Especially sound and Quartz programming on the IPhone. Thanks!
I have to develop an iPhone application at my company which would sync data to and from PC/Mac. Can you guide me as to how to start and proceed with this? Would appreciate a tutorial on this but since you seem to already have some tutorials of your own lined up, only an overview will do. Just tell me which classes/methods etc should i use. Thank you.
Just F.Y.I, you can get a better screen capture of the iPhone simulator if you press Command+Shift+4 (you will get the cross hairs), then you press space bar to get a camera icon. Click on the iPhone simulator and you won’t have borders or background. It will even add a nice drop shadow!
*** Terminating app due to uncaught exception ‘NSInternalInconsistencyException’, reason: ‘-[UIViewController _loadViewFromNibNamed:bundle:] loaded the “iTennisViewController” nib but the view outlet was not set.’
I think you have not set your iTennisViewControllers view to the delegate. please check wheather it is set or not. you just open iTennisViewController.xib file, click the file owner , open the inspector ( apple + shift + i) go to the second tab. there you will find connections. check if the connection is made or not. or somewhere you have missed something.
Hey Everyone,
I’m still not able to get anything to show up other than the court image… I’ve looked through the threads, people seemed to have documented that they figured it out, but have not posted any solutions… any help for a noob?
hi brandon,
I am waiting for the next part,
please let me know how much more time will it take,
truely i cant wait for that
for a long time i m searching for a game tutorial,
but i didnt get it, through this i will be able to learn a lot.
please reply
thanks a lot
I’d like to see declaration & usage of objects/methods/functions… reading and passing arguments from said classes.
Most iPhone blog/books only discuss programming the interface and the books I have on cocoa are written for Mac. The code is not 100% compatible with iPhone.
For example… I have HilleGass’ book on ‘cocoa for mac’ I can write classes and function and pass arguments that work excellent on the mac but comes up with tons of errors when you try it on the iPhone.
It’s just that the syntax for the iPhone is a little different so basic examples that demonstrate how to do it would work fine.
I’m sorry you didn’t understand my first post. I was hoping you could do a primer on “How to create objects and methods – and implement them” tutorial.
I just reviewed the Fruit App and it’s a great intro. The reason I’m asking is because you are great at explaining stuff so we can understand it.
Thanks for the great tutorials!!!!
Examples of the primer:
How to create an object…
How to pass a message to an object…
Methods that return multiple values…
Methods that return no value…
Creating an instance…
How to get an object’s data…
Creating pointers to objects…
It’s a kind of ‘how to do anything with objects’ thing.
Thanks a lot Brandon! This is my second day of learning IPhone programming and I think your site is one of the easiest to follow.
So, I know this is probably totally wrong and off, but for those who were wondering about how to simulate collision and move the paddle this is what I did:
1) In the Interface Builder, make sure you select the paddle and then in the Image View Attributes window, check the “User Interaction Enabled” checkbox.
2) I added this function to iTennisViewController.m:
Is there some sort of Javadoc format website for the classes in the IPhone? I use XCode and the “Jump To Definition” menu link, but I figure there must be a better way?
Hey, I just finished up the tutorial and when I Build and Go, I get the loading screen and then just a white background… No errors or warnings. Any ideas??
I know this will sound like a stupid question, but if you get a phone call will this app close? or is there some code you need to implement some sort of “got a phone call” method?
Yes offcourse application will quit, becuase in iphone only one application will run at one time, so if you get a phone call this application will quit untill we override applicationWillTerminate method, there we need to store our current face so that after phone call or sms ends application will run from the point where you got a call or sms. correct me if I am wrong.
is working , i tried and debugged this condition is not getting setisfied. if you want that whenever you touch the screen and move you finger then only yellow racquet will move then replace
if([touch view ] == self.view) or if you want that when you touch then only raquet will move then try
Any app will automatically exit when you get a phone call. This is implemented by iphone OS by itself. So there is no way you can keep your application running if you get a call.
Ok so I implemented some thing to work, it is working ,but you try it and make some changes as per your comfort, make your own rules. I just try to implement working of yellow racquet, ball is coming touching to yellow racquet, and diverted towards the green racquet, did not code for green racquet. so lets start. first you need to declare one more variable in tennisviewcontroller.h
IBOutlet UILabel *player_score;
declare its property like
@property(nonatomic) NSInteger pscore;
synthesize it in .n file,
synthesize pscore;
now implement
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
I completed the functionality of computer’s racquet o.e green racquet. first make a variable like pscore. declare its property and synthesize it.
open your iTennisViewController.xib file and move your green racquet to the left corner and ball from center to top left corner below your racquet . this will give you a feel that computer is serving you the ball to play make sure that ball and racquet are not overlapping,maintain some distance between them, now open iTennisViewController.m file, you already have synthesize the cscore, in view did load method
write cscore = 0;
now make changes in gameloop method. here is the code, compare it with previous.
In my previous post where i posted the code for yellow_racquet
i told you to declare the variable and i missed that to paste there, that variable is
NSInteger *pscore;
and other is NSInteger *cscore;
initialize them in viewDidLoad as
pscore = 0;
cscore = 0;
I am using these scores only that user can understand our ball is hitting to racquets. these are for temporary use. if you dont want to show you can leave this step.
please update, if any other mistake or the code is throwing error anything please let me know.
Thanks.
@Chintan “So there is no way you can keep your application running if you get a call.”
I don’t want to keep it running. In fact I just wanted to make sure it would not keep running. I don’t have an iphone but rather plan on getting a ipod touch to test with, so I won’t be able to test what happens if I get a call. So I just wanted to check.
Im having a problem when I launch in iPhone Simulator when its LOADING it stops and says “The application iTennis quit unexpectedly and says Ignore , report, Relaunch.” So thats the deal I made sure the connections are made. There is a few that are not and I dont know if they nee to be they are ” view, tabBarItem,navigationalItem.”
SO if they need to be please let me know as I am very new to programing and apps. I have very carefully checked and rechecked the code so I dont think it’s there, but I could very well be wrong. Thanks for your help.
Your problem is in the code somewhere. In order to help you you need to give more information. When you launch you application make sure your console is displayed, Run > Console or Shift Command R. This will give you debugging information about why you app is crashing on launch.
thank you for this… i hope you continue. I am having a basic problem with IB. When I drag the second Image View onto the View Controller it replaces the ‘court’ image and does not go on top of it. I also have more icons in my MainWindow.xib folder.
I have…
file’s owner
First Responder
iTennis App Delegate
iTennis View Controller
Window
these are more than what you have in your video. ANY help would be greatly appreciated. Is the view controller delegate supposed to be a delegate to the file’s owner? If so, i cannot set it that way. right now, view controller is delegate to app delegate and app delegate is delegate to file’s owner….
help????
ok… fixed that problem I think, by restarting IB through xcode….wierd. Now I get this in the console…
*** Terminating app due to uncaught exception ‘NSUnknownKeyException’, reason: ‘[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key raquet_yellow.’
Not sure what is wrong with raquet_yellow. I’ve checked the code and there are no build errors, and the connections seem ok.
@Brandon:
First of all love your tutorials and have be searching for a basic game tut for some time. Can’t wait for the next installment.
I was just wondering if you could include some standard features that most games include like a splash screen and menu. I know iTennis doesn’t really need it but it would relate well to the many people who would use this series of tutorials in creating their games.
@Robert
please check that you have defined properties properly, like for racquet_yellow
IBOutlet UIImageView *racquet_yellow;
then
@property(nonatomic,retain)IBOutlet UIImageView *ra……;
and in the .m file
@synthesize racquet.
check might be some spelling mistake, or pointer is not there or in .m property you have put pointer there. check for these issues.
[...] iPhone Game Programming Tutorial – Part 1 | iCodeBlog [...]
By on March 24, 2009 at 12:22 pm
[...] 33. iPhone game programming [...]
By on April 14, 2009 at 1:14 am
[...] tutorial has three parts, the first part deals with the creation of different folders within the main project folder. The second part [...]
By on July 5, 2009 at 6:25 am
[...] iPhone Game Programming Tutorial: This multipart tutorial offers a way to learn OpenGL and Quartz for iPhone development. [iCode] [...]
By on July 9, 2009 at 1:43 am
[...] of Brandon’s most popular articles is the “iPhone Game Programming Tutorial” in which he gives step-by-step instructions on how to build an iPhone game called iTennis (a [...]
By on July 9, 2009 at 7:00 pm
[...] ripoff of code provided by the iCodeBlog, a site known for its free iPhone coding tutorials. The original tutorial, written by Brandon Trebitowski, was apparently compiled and submitted by Peter Sheen of [...]
By on July 9, 2009 at 7:45 pm
[...] ripoff of code provided by the iCodeBlog, a site known for its free iPhone coding tutorials. The original tutorial, written by Brandon Trebitowski, was apparently compiled and submitted by Peter Sheen of [...]
By on July 9, 2009 at 7:47 pm
[...] ripoff of code provided by the iCodeBlog, a site known for its free iPhone coding tutorials. The original tutorial, written by Brandon Trebitowski, was apparently compiled and submitted by Peter Sheen of [...]
By on July 9, 2009 at 7:48 pm
[...] ripoff of code provided by the iCodeBlog, a site known for its free iPhone coding tutorials. The original tutorial, written by Brandon Trebitowski, was apparently compiled and submitted by Peter Sheen of [...]
By on July 9, 2009 at 8:06 pm
[...] ripoff of code provided by the iCodeBlog, a site known for its free iPhone coding tutorials. The original tutorial, written by Brandon Trebitowski, was apparently compiled and submitted by Peter Sheen of [...]
By on July 9, 2009 at 8:15 pm
[...] ripoff of code provided by the iCodeBlog, a site known for its free iPhone coding tutorials. The original tutorial, written by Brandon Trebitowski, was apparently compiled and submitted by Peter Sheen of [...]
By on July 10, 2009 at 12:20 am
[...] ripoff of code provided by the iCodeBlog, a site known for its free iPhone coding tutorials. The original tutorial, written by Brandon Trebitowski, was apparently compiled and submitted by Peter Sheen of [...]
By on July 10, 2009 at 6:49 am
[...] Yeah, that’s right: stolen code. The code came from a tutorial site called iCodeBlog, and the tutorial containing this code was written by Brandon Trebitowski. A company on the App Store called [...]
By on July 15, 2009 at 7:04 pm
[...] ripoff of code provided by the iCodeBlog, a site known for its free iPhone coding tutorials. The original tutorial, written by Brandon Trebitowski, was apparently compiled and submitted by Peter Sheen of [...]
By on July 27, 2009 at 8:50 am
[...] Devs”. La versione originale inglese del tutorial è disponibile a questo indirizzo: “iPhone Game Programming Tutorial, Part 1 – iCodBlog“. I meriti quindi relativamente alla versione inglese, sono del legittimo [...]
By on August 19, 2009 at 1:24 pm
[...] iPhone Game Programming Tutorial – Part 1 [...]
[...] might recognize this “game” from a tutorial that I wrote about writing an iPhone game (link). One thing to note here is the company name is BlaBlaIncTech (not iCodeBlog) meaning I did not [...]
By on October 4, 2009 at 4:48 pm
[...] Part one explains basic use of xCode and Interface Builder. He also demonstrated some basic game design framework. Part two talks about user interactions. Part three discusses about putting a Splash screen to an applicaiton. [...]
By on October 20, 2009 at 9:25 pm
[...] iPhone Game Programming Tutorial: This multipart tutorial offers a way to learn OpenGL and Quartz for iPhone development. [iCode] [...]
By on November 24, 2009 at 1:58 am
[...] iPhone Game Programming Tutorial: Part 1 Here’s a complete tutorial for creating a Pong-like iPhone game. [...]
By on November 30, 2009 at 1:50 am
[...] iPhone Game Programming Tutorial: Part 1 Here’s a complete tutorial for creating a Pong-like iPhone game. [...]
By on January 21, 2010 at 5:11 pm
[...] I named this application “Galactic Pong” but in essence it is just a edited version of “iTennis” but the author of that tutorial. You can access that tutorial here. [...]
By on January 29, 2010 at 5:03 am
[...] iPhone Game Programming Tutorial – Part 1 | iCodeBlog (tags: iphone programming) [...]
By on January 29, 2010 at 9:02 am
[...] up XCode and create a View Based Application. Name this application iTennis. After you unzip all of the images, drag them into the project [...]
By on February 1, 2010 at 7:57 pm
[...] iPhone Game Programming Tutorial: Part 1 Here’s a complete tutorial for creating a Pong-like iPhone game. [...]
By on March 6, 2010 at 9:05 am
[...] iPhone Game Programming – Part one of a 4-part series on creating your first iPhone Game. Create a simple pong style game and learn about collision detection, sounds, AI and user interaction in the process. [...]
177 Comments
Hey Brandon
congrats on your new job
.
any approximate idea how many tutorials you will publish in this series and how long it will take. Just some approximate ideas so that we can buckle up for the ride.
One small suggestion, maybe you can post some small assignment type questions so that we can do play around on our own too
.
Cant wait for you to finish the tutorials. Congrats by the way.
This is exactly the kind of think I am looking for. I am totally new to Objective-C and the OSX and iPhone Frameworks. (only did windows development before)
I think pong is an excellent “hello world” for writing games as it contains many basics. As you already pointed out however it doesn’t include any animation/sprite type examples. Any chance you could toss in a small animation example? Maybe have the raquets change color or something when they collide with the ball or something simple?
I look forward to the rest of this series!
Thanks for writing this, I look forward to reading more game tutorials.
Hi Brandon!
I’m also new to the Mac “world”, your tutorial came in the right moment.
I’m having trouble though, when I run iTennis it crashes and generates a report to send to Apple. Can you help me find out what am I doing wrong? The build shows no errors nor warnings.
Thanks and keep up the good work!
Just to give you more information, look what I’ve found on the report it generates to Apple:
*** Terminating app due to uncaught exception ‘NSInternalInconsistencyException’, reason: ‘-[UIViewController _loadViewFromNibNamed:bundle:] loaded the “iTennisViewController” nib but the view outlet was not set.’
Great tutorial as always. I’m looking forward to seeing more of the obscure aspects of game programming as well. Especially sound and Quartz programming on the IPhone. Thanks!
Hi Brandon,
I have to develop an iPhone application at my company which would sync data to and from PC/Mac. Can you guide me as to how to start and proceed with this? Would appreciate a tutorial on this but since you seem to already have some tutorials of your own lined up, only an overview will do. Just tell me which classes/methods etc should i use. Thank you.
Yes! I have been searching the net for a single iPhone game tutorial! This is exactly what I need! Keep up the great work!
Cool! when will the next tutorial in the series come out?
This is just what I was looking for! As a game developer trying to transfer my knowledge of simple game loops, this provided a really good foundation.
Please, please, please give us more
Really great tutorial- looking forward to the next in the series.
Please please please continue this wonderful tutorial! Thank you so much. I have learned a lot about Objective C by just doing this tutorial.
g
Great tutorial, but I also have the same problem where it crashes when I go to launch. Any one know why?
This was a great tutorial. I can’t wait for the next in the series. I will try to get the paddle working on my own until then.
Just F.Y.I, you can get a better screen capture of the iPhone simulator if you press Command+Shift+4 (you will get the cross hairs), then you press space bar to get a camera icon. Click on the iPhone simulator and you won’t have borders or background. It will even add a nice drop shadow!
Hi,
It is really a nice one,
great tutorial, cant wait for its part 2,
when it will be here on icodeblog,
thanks for all your efforts.
hi Andre ,
*** Terminating app due to uncaught exception ‘NSInternalInconsistencyException’, reason: ‘-[UIViewController _loadViewFromNibNamed:bundle:] loaded the “iTennisViewController” nib but the view outlet was not set.’
I think you have not set your iTennisViewControllers view to the delegate. please check wheather it is set or not. you just open iTennisViewController.xib file, click the file owner , open the inspector ( apple + shift + i) go to the second tab. there you will find connections. check if the connection is made or not. or somewhere you have missed something.
Hey Everyone,
I’m still not able to get anything to show up other than the court image… I’ve looked through the threads, people seemed to have documented that they figured it out, but have not posted any solutions… any help for a noob?
thanks in advance!
great tutorial but same like ball from standford, pls finish next part , thanks
hi brandon,
I am waiting for the next part,
please let me know how much more time will it take,
truely i cant wait for that
for a long time i m searching for a game tutorial,
but i didnt get it, through this i will be able to learn a lot.
please reply
thanks a lot
narender.mudgal, thanks a lot, that did the trick. Thanks!
Looking forward for the next part of the tutorial!
Hi Brandon.
I’d like to see declaration & usage of objects/methods/functions… reading and passing arguments from said classes.
Most iPhone blog/books only discuss programming the interface and the books I have on cocoa are written for Mac. The code is not 100% compatible with iPhone.
For example… I have HilleGass’ book on ‘cocoa for mac’ I can write classes and function and pass arguments that work excellent on the mac but comes up with tons of errors when you try it on the iPhone.
It’s just that the syntax for the iPhone is a little different so basic examples that demonstrate how to do it would work fine.
Thanks
@DN,
I’m not sure I understand what you are asking. If you look at my site, all of the tutorials involve writing code for the iPhone…
Hey, thanks for the tutorial. It’s a great start and put together nicely. I’m looking forward to seeing more.
hey,
great tutorials! you’re blog has become my one-stop guide for the app i am working on! keep up the great work!
btw, great wallpaper on the video ? can I download it somewhere ??
ck
Brandon,
I’m sorry you didn’t understand my first post. I was hoping you could do a primer on “How to create objects and methods – and implement them” tutorial.
I just reviewed the Fruit App and it’s a great intro. The reason I’m asking is because you are great at explaining stuff so we can understand it.
Thanks for the great tutorials!!!!
Examples of the primer:
How to create an object…
How to pass a message to an object…
Methods that return multiple values…
Methods that return no value…
Creating an instance…
How to get an object’s data…
Creating pointers to objects…
It’s a kind of ‘how to do anything with objects’ thing.
Thanks again.
Thanks a lot Brandon! This is my second day of learning IPhone programming and I think your site is one of the easiest to follow.
So, I know this is probably totally wrong and off, but for those who were wondering about how to simulate collision and move the paddle this is what I did:
1) In the Interface Builder, make sure you select the paddle and then in the Image View Attributes window, check the “User Interaction Enabled” checkbox.
2) I added this function to iTennisViewController.m:
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [[event allTouches] anyObject];
CGPoint touchLocation = [touch locationInView:self.view];
if([touch view] == raquet_yellow) {
raquet_yellow.center = touchLocation;
}
}
3) in the gameLoop function, I changed it to:
-(void)gameLoop {
if(gameState == kGameStateRunning) {
ball.center = CGPointMake(ball.center.x + ballVelocity.x, ball.center.y + ballVelocity.y);
if(ball.center.y > self.view.bounds.size.height || ball.center.y self.view.bounds.size.width || ball.center.x < 0) {
ballVelocity.x = -ballVelocity.x;
}
CGRect raquet_rect = CGRectMake(raquet_yellow.center.x, raquet_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;
}
}
}
Is there some sort of Javadoc format website for the classes in the IPhone? I use XCode and the “Jump To Definition” menu link, but I figure there must be a better way?
Thanks for tut but the video doesnt work
@masterjcl
Thats means you don’t have the latest version of quicktime. Download that and the video will work.
@ck
Found it on google images… Not exactly sure where.
@DN
That’s a good idea… Apple has a pretty good doc on this, I think it’s called objective C primer.
@ Joe
There is, it’s actually built right in to XCode.
Press Apple-option-shift-?
This should bring up the doc. It’s not quite as good as Javadoc, but it’s still pretty helpful.
Hi, Brandon…
i found the answer to what i asked…
Such an application is not possible to develop. Since OS 2.1 update, applications are not allowed to read or write other applications data…
Its not possible for any 2 applications on an iphone to communicate with each other in any way. Except for Apple’s own apps…
Hey, I just finished up the tutorial and when I Build and Go, I get the loading screen and then just a white background… No errors or warnings. Any ideas??
Awesome tutorial!
I can’t wait for the second part. Do you have any idea as to when you’ll post it?
Thanks again for the tutorial!
I know this will sound like a stupid question, but if you get a phone call will this app close? or is there some code you need to implement some sort of “got a phone call” method?
Yes offcourse application will quit, becuase in iphone only one application will run at one time, so if you get a phone call this application will quit untill we override applicationWillTerminate method, there we need to store our current face so that after phone call or sms ends application will run from the point where you got a call or sms. correct me if I am wrong.
Thanks
Hi Joe,
i tried with your code,
in touch moved are you sure
if([touch view] == raquet_yellow) {
raquet_yellow.center = touchLocation;
}
is working , i tried and debugged this condition is not getting setisfied. if you want that whenever you touch the screen and move you finger then only yellow racquet will move then replace
if([touch view ] == self.view) or if you want that when you touch then only raquet will move then try
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [touches anyObject];
if(CGRectContainsPoint([racquet_yellow frame], [touch locationInView:self.view]))
{
[self moveSquare:racquet_yellow toPoint:[touch locationInView:self.view]];
}
@Rey…
Any app will automatically exit when you get a phone call. This is implemented by iphone OS by itself. So there is no way you can keep your application running if you get a call.
Ok so I implemented some thing to work, it is working ,but you try it and make some changes as per your comfort, make your own rules. I just try to implement working of yellow racquet, ball is coming touching to yellow racquet, and diverted towards the green racquet, did not code for green racquet. so lets start. first you need to declare one more variable in tennisviewcontroller.h
IBOutlet UILabel *player_score;
declare its property like
@property(nonatomic) NSInteger pscore;
synthesize it in .n file,
synthesize pscore;
now implement
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [touches anyObject];
if(CGRectContainsPoint([racquet_yellow frame], [touch locationInView:self.view]))
{
[self moveRacquet:racquet_yellow toPoint:[touch locationInView:self.view]];
}
}
and make some changes in gameloop method.
I made it like
-(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;
}
if(CGRectContainsPoint([racquet_yellow frame], ball.center) )
{
self.pscore += 10;
player_score.text = [NSString stringWithFormat:@"%i",self.pscore + 10];
// ballVelocity.x = -ballVelocity.x;
ballVelocity.y = -ballVelocity.y;
if(ball.center.x <= self.view.center.x)
{
ballVelocity.x = 3;
}
else
{
ballVelocity.x = -3;
}
}
}else{
if(tapToBegin.hidden){
tapToBegin.hidden = NO;
}
}
}
and here is the moveRacquet method
-(void)moveRacquet:(UIImageView *)view toPoint:(CGPoint)location{
view.center = location ;
}
declare this method in .h file like
-(void)moveRacquet:(UIImageView *)view toPoint:(CGPoint)location;
now run the project move your racquet , still there is a lot to do. please comment and correct my work.
Thanks
one thing i left
in viewdidload
self.pscore = 0; initialize the playerscore with zero i will continue with green_racquet functionality
I completed the functionality of computer’s racquet o.e green racquet. first make a variable like pscore. declare its property and synthesize it.
open your iTennisViewController.xib file and move your green racquet to the left corner and ball from center to top left corner below your racquet . this will give you a feel that computer is serving you the ball to play make sure that ball and racquet are not overlapping,maintain some distance between them, now open iTennisViewController.m file, you already have synthesize the cscore, in view did load method
write cscore = 0;
now make changes in gameloop method. here is the code, compare it with previous.
-(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;
}
if(ball.center.y <= self.view.center.y)
{
CGPoint ballx = CGPointMake(ball.center.x,racquet_green.center.y);
[racquet_green setCenter:ballx];
}
if(CGRectContainsPoint([racquet_green frame], ball.center))
{
cscore += 10 ;
computer_score.text = [NSString stringWithFormat:@"%i", self.cscore + 10];
ballVelocity.y = -ballVelocity.y;
if(ball.center.x <= self.view.center.x) {
ballVelocity.x = random() % 9 ;
}else{
ballVelocity.x = -(random() % 9) ;
}
}
if(CGRectContainsPoint([racquet_yellow frame], ball.center) )
{
self.pscore += 10;
player_score.text = [NSString stringWithFormat:@"%i",self.pscore + 10];
ballVelocity.y = -ballVelocity.y;
if(ball.center.x <= self.view.center.x) {
ballVelocity.x = random() % 9;
}else{
ballVelocity.x = -(random() % 9);
}
}
}else{
if(tapToBegin.hidden){
tapToBegin.hidden = NO;
}
}
}
also increase the ball’s speed
#define kBallSpeedX 10
#define kBallSpeedY 25
Thanks
In my previous post where i posted the code for yellow_racquet
i told you to declare the variable and i missed that to paste there, that variable is
NSInteger *pscore;
and other is NSInteger *cscore;
initialize them in viewDidLoad as
pscore = 0;
cscore = 0;
I am using these scores only that user can understand our ball is hitting to racquets. these are for temporary use. if you dont want to show you can leave this step.
please update, if any other mistake or the code is throwing error anything please let me know.
Thanks.
When will part 2 be out? I really wana finish this.
@Chintan “So there is no way you can keep your application running if you get a call.”
I don’t want to keep it running. In fact I just wanted to make sure it would not keep running. I don’t have an iphone but rather plan on getting a ipod touch to test with, so I won’t be able to test what happens if I get a call. So I just wanted to check.
@Rey..
If you dont want to keep it running then you dont need to worry about it.. Like i said, iPhone takes care of that by itself.
Im having a problem when I launch in iPhone Simulator when its LOADING it stops and says “The application iTennis quit unexpectedly and says Ignore , report, Relaunch.” So thats the deal I made sure the connections are made. There is a few that are not and I dont know if they nee to be they are ” view, tabBarItem,navigationalItem.”
SO if they need to be please let me know as I am very new to programing and apps. I have very carefully checked and rechecked the code so I dont think it’s there, but I could very well be wrong. Thanks for your help.
Clad,
Your problem is in the code somewhere. In order to help you you need to give more information. When you launch you application make sure your console is displayed, Run > Console or Shift Command R. This will give you debugging information about why you app is crashing on launch.
thank you for this… i hope you continue. I am having a basic problem with IB. When I drag the second Image View onto the View Controller it replaces the ‘court’ image and does not go on top of it. I also have more icons in my MainWindow.xib folder.
I have…
file’s owner
First Responder
iTennis App Delegate
iTennis View Controller
Window
these are more than what you have in your video. ANY help would be greatly appreciated. Is the view controller delegate supposed to be a delegate to the file’s owner? If so, i cannot set it that way. right now, view controller is delegate to app delegate and app delegate is delegate to file’s owner….
help????
ok… fixed that problem I think, by restarting IB through xcode….wierd. Now I get this in the console…
*** Terminating app due to uncaught exception ‘NSUnknownKeyException’, reason: ‘[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key raquet_yellow.’
Not sure what is wrong with raquet_yellow. I’ve checked the code and there are no build errors, and the connections seem ok.
@Brandon:
First of all love your tutorials and have be searching for a basic game tut for some time. Can’t wait for the next installment.
I was just wondering if you could include some standard features that most games include like a splash screen and menu. I know iTennis doesn’t really need it but it would relate well to the many people who would use this series of tutorials in creating their games.
Cheers
mayhem_nz
@Robert
please check that you have defined properties properly, like for racquet_yellow
IBOutlet UIImageView *racquet_yellow;
then
@property(nonatomic,retain)IBOutlet UIImageView *ra……;
and in the .m file
@synthesize racquet.
check might be some spelling mistake, or pointer is not there or in .m property you have put pointer there. check for these issues.
27 Trackbacks
[...] iPhone Game Programming Tutorial – Part 1 | iCodeBlog [...]
[...] 33. iPhone game programming [...]
[...] tutorial has three parts, the first part deals with the creation of different folders within the main project folder. The second part [...]
[...] iPhone Game Programming Tutorial: This multipart tutorial offers a way to learn OpenGL and Quartz for iPhone development. [iCode] [...]
[...] of Brandon’s most popular articles is the “iPhone Game Programming Tutorial” in which he gives step-by-step instructions on how to build an iPhone game called iTennis (a [...]
[...] ripoff of code provided by the iCodeBlog, a site known for its free iPhone coding tutorials. The original tutorial, written by Brandon Trebitowski, was apparently compiled and submitted by Peter Sheen of [...]
[...] ripoff of code provided by the iCodeBlog, a site known for its free iPhone coding tutorials. The original tutorial, written by Brandon Trebitowski, was apparently compiled and submitted by Peter Sheen of [...]
[...] ripoff of code provided by the iCodeBlog, a site known for its free iPhone coding tutorials. The original tutorial, written by Brandon Trebitowski, was apparently compiled and submitted by Peter Sheen of [...]
[...] ripoff of code provided by the iCodeBlog, a site known for its free iPhone coding tutorials. The original tutorial, written by Brandon Trebitowski, was apparently compiled and submitted by Peter Sheen of [...]
[...] ripoff of code provided by the iCodeBlog, a site known for its free iPhone coding tutorials. The original tutorial, written by Brandon Trebitowski, was apparently compiled and submitted by Peter Sheen of [...]
[...] ripoff of code provided by the iCodeBlog, a site known for its free iPhone coding tutorials. The original tutorial, written by Brandon Trebitowski, was apparently compiled and submitted by Peter Sheen of [...]
[...] ripoff of code provided by the iCodeBlog, a site known for its free iPhone coding tutorials. The original tutorial, written by Brandon Trebitowski, was apparently compiled and submitted by Peter Sheen of [...]
[...] Yeah, that’s right: stolen code. The code came from a tutorial site called iCodeBlog, and the tutorial containing this code was written by Brandon Trebitowski. A company on the App Store called [...]
[...] ripoff of code provided by the iCodeBlog, a site known for its free iPhone coding tutorials. The original tutorial, written by Brandon Trebitowski, was apparently compiled and submitted by Peter Sheen of [...]
[...] Devs”. La versione originale inglese del tutorial è disponibile a questo indirizzo: “iPhone Game Programming Tutorial, Part 1 – iCodBlog“. I meriti quindi relativamente alla versione inglese, sono del legittimo [...]
[...] iPhone Game Programming Tutorial – Part 1 [...]
[...] iTennis这个教程还不错,虽然没用上什么华丽复杂的功能,但是一步一步跟着做下去,对于怎么做出一个iPhone游戏还是很有帮助的。这也是我除了Hello World之外第一个自己尝试的iPhone App了。虽然Object-C的挺多语句还不很习惯,也有一些不理解的地方,但确实感受到了,开发iPhone的项目门槛并不高。这也给自己树立了信心,有机会好好学习和开发iPhone软件。如果有时间,我也自己写一个关于自己开发软件的教程。 [...]
[...] might recognize this “game” from a tutorial that I wrote about writing an iPhone game (link). One thing to note here is the company name is BlaBlaIncTech (not iCodeBlog) meaning I did not [...]
[...] Part one explains basic use of xCode and Interface Builder. He also demonstrated some basic game design framework. Part two talks about user interactions. Part three discusses about putting a Splash screen to an applicaiton. [...]
[...] iPhone Game Programming Tutorial: This multipart tutorial offers a way to learn OpenGL and Quartz for iPhone development. [iCode] [...]
[...] iPhone Game Programming Tutorial: Part 1 Here’s a complete tutorial for creating a Pong-like iPhone game. [...]
[...] iPhone Game Programming Tutorial: Part 1 Here’s a complete tutorial for creating a Pong-like iPhone game. [...]
[...] I named this application “Galactic Pong” but in essence it is just a edited version of “iTennis” but the author of that tutorial. You can access that tutorial here. [...]
[...] iPhone Game Programming Tutorial – Part 1 | iCodeBlog (tags: iphone programming) [...]
[...] up XCode and create a View Based Application. Name this application iTennis. After you unzip all of the images, drag them into the project [...]
[...] iPhone Game Programming Tutorial: Part 1 Here’s a complete tutorial for creating a Pong-like iPhone game. [...]
[...] iPhone Game Programming – Part one of a 4-part series on creating your first iPhone Game. Create a simple pong style game and learn about collision detection, sounds, AI and user interaction in the process. [...]