I have noticed recently many people wanting to create games for the iPhone and are unsure where to start. A common misconception is that you must use OpenGL ES to create any game with graphics. I am going to show you today how you can do some simple animation by moving a ball around the screen. We will not be using OpenGL ES to move the ball. We will simply be using an NSTimer and a UIImageView.
The code for this could be used in many game applications. Games such as pong, brick breaker, etc… I will soon do an iPhone game programming tutorial series. For now, here is a quick tutorial to get you started and excited…
You will need to download this image for this tutorial:
Here are the steps involved in creating this application:
Start With a View-Based Application
We will not need any navigation components for this app. All we need is a view that we can add a UIImageView to.
Add The Ball Image To Your Project
You can use any image you would like for this. I used my mad skills in Photoshop to create a shiny red ball for you to use. This will be the image that we will be “bouncing” around the screen.
Add An IBOutlet For the Ball
This step is necessary as it allows us the link the ball we add to the view in Interface Builder to the code. This is so we can update the position of the ball at each timestep.
Add The Ball To The View In Interface Builder
All we need to draw the ball on the screen is a UIImageView. Since we added the ball.png file to our project, it should appear in the drop-down in the attributes section of the UIImageView. Also, at this step, we need to connect the UIImageView to the ‘ball’ variable by dragging from ‘new referencing outlet’ in the connection inspector of the UIImageView to the ‘File’s Owner’ object.
Add The Code To Initialize The NSTimer
An NSTimer is very simple to use. It simple requires that you specify an interval (I used .05) and a function to call at each time-step. The function we are calling in this tutorial is the onTimer function. This is a function that we create and will contain the logic to move the ball.
Moving The Ball
This code is all fairly straight forward. First we add the pos.x and pos.y values (14.0 and 7.0) to the center of the ball object this causes the ball to move diagonally. Next we simply check to see if the ball has collided with the wall. If the ball does collide with the wall, we simple reverse the pos.x or the pos.y.
That concludes the animation tutorial. I hope that you go out an make lots of great games after this… Soon, I will start another tutorial series where I we will be creating a full blown game. If you have any suggestions for games, please leave them in the comments. Make sure that they are fun but not too in depth, we need to limit the series. Think in terms of pong, asteroids, etc…
You can download the source code here . If you have any comments or questions, feel free to leave them in the comments of this post. You may also post them in the forums. Happy iCoding!

I have noticed recently many people wanting to create games for the iPhone and are unsure where to start. A common misconception is that you must use OpenGL ES to create any game with graphics. I am going to show you today how you can do some simple animation by moving a ball around the screen. We will not be using OpenGL ES to move the ball. We will simply be using an NSTimer and a UIImageView.
86 Comments
Thanks for the tutorial. It is the first one that has been a success so far.
Is there any way to make a copy of a graphic–kinda like tiling? Lets say you wanted 15 balls flying around…
Thanks,
Marv
Ya, just dynamically allocate each of the UIImageView s and set the attributes with code. Just call each of your image views in the code instead of just one
Excuse me ., i want ask outside this topic.
what is your use software for capture this tutorial.
example. I use snagit 9 for capture but i upload to youtube the quality for VDO is very low and can not zoom for focus area.
Isn’t this just a remake of the tutorial trailsinthesand.com posted? Perhaps you should give a shout out if you are going to steal others work.
Hi, Im using the latest SDK which I downloaded today, and Im having problems with this. I get multiple errors such as “error ‘pos’ undeclared (first use in this function)” even though i declared CGPoint = pos; in the ballviewcontroller.h file. There are also other errors like under this line:
#import “BallViewControllerViewController.h”
it says syntax error before “=” token, and warning – decleration does not declare anything. I didnt even change anything in this line, so I dont know why it’s giving an error. I did the whole thing 2 full times, and I still get errors. Is it becasue I have a newer version of the sdk? I just started programming today, so I have no idea what to do. Can someone please help me. Thanks. Btw, this site is an amazing resource for someone like me! Thanks for all your tutorials!
Thank you very much for your work. Very appreciated. Great tutorials!
Hi,
a bit offtopic but:
do you still have that awesome background you use on you Mac? I’d love to have it.
If you could perhaps mail it to me that’d be great.
Great tutorial…unfortunately I did something similar just the other day and it gave me errors in the simulator
Gotta figure out what I did wrong I guess.
Hi,
Great tutorials, keep up the good work.
Only one issue with this, ive followed the tutorial closely & downloaded the sample code. Both seem to build in xcode, but when the simulator launched the app, the simulator quits unexpectedly?
Any suggestions, anyone?
Thanks
I think its difficult to write the games using this simple animation. Its like discovering the wheel again. Even for simple games v must write plenty of code. To learn about UIView animation its good way to design the games using UIView animation. If u guys really want to make games den v must use other technology isn’t it?
Hi, just wondering how would you implement a start and stop button for this, so when the app starts the ball is stationary. But when a start button is pressed it starts moving Btw I’m an iphone SDK noob.
What if you wanted to add buttons on that view to start and stop the ball from moving? How would you stop the onTimer event?
DOH!!! Should have looked directly above…. sorry
DOH!!! Should have looked directly above…. sorry
Excellent job Brandon, just starting iphone development and your tutorials are fantastic. Thanks for taking the time and effort to put them in.
Nice tutorial, you make it look easy.
Hi,
thank’s for the tutorial,
I’m am a new developer I’m using iphone sdk to develop a kind of sudocku application. I would like to have sugestion how to implement and controll my table with many rows and coloms.
Excellent tutoial! How would i go about making the ball react to touch? as in the ball bounces off the area touched.
Hi Brandon
Ive found your tutorials very useful, but im having trouble with this one. Ive tried it a few times and im get 5 errors every time. Is this tutorial on an old version of the sdk. I have the most up to date version. Have been able to get others to work, but this just wont…
Thanks
Hi! I really like this tutorial! But I am wondering how o make multiple balls. I want to see 4 ball in my screen moving!
Please help in this!
Thanks!
awesome tutorial, its just given me an insight into how powerful the built in functions are and how easy it is to animate. I am new to iphone app development and its tutorials like this that keep me pushing on. thanks.
Thanks a stack for these tutorials. These are real ‘light at the end of the tunnel’ tuts. I can’t tell you how good it was to find this site: your efforts are MUCH appreciated!!
can you programatically add the image of the ball instead of adding it through interface builder?
Hi!
Great tutorial! I just have question…I have made my first app now and I really have no idea how to export it to iTunes and then to my iPhone. Would be really happy with an answer. Please notify me via email if you answer this post. Thanks!
@geniexy2132 Yes, you can programmatically add an image instead of doing it through Interface Builder. First just create an UIImageView in your .h file and add a property and synthesize it in the .m. Note you do not have to do an IBOutlet. To add the image go to the .m file and add
ball.image = [UIImage imageNamed:@"ball.png"];
That’s it.
Awesome tutorial! The only problem I’m having is its when I go to drag the new reference thing it only lets me choose View, not ball. What did I do wrong? Thanks!
Memory leaks…
I am very new to iPhone programming. I am looking for a tutorial like where we can scale objects on the screen when they are touched and then once the user lifts the finger then it stops. wonder how to do that any suggestion please help.
I organize this collection to be unequivocally useful. I am using it in a report I am article at college.
la martina
Code update for 3.2, shows how to construct NSInvocation.
- (void)viewDidLoad {
pos = CGPointMake(14.0, 7.0);
SEL selector = @selector(onTimer);
NSMethodSignature *aSig = [self methodSignatureForSelector:selector];
NSInvocation *anInvo = [NSInvocation invocationWithMethodSignature:aSig];
anInvo.selector = selector;
anInvo.target = self;
[NSTimer scheduledTimerWithTimeInterval:0.05 invocation:anInvo repeats:YES];
// [super viewDidLoad];
}
Thanks for all the time and work you put into these tutorials.
I’m sure you realize how valuable they are to beginning programmers, otherwise you would not create them, and they would not be as illuminating as they are.
Its amazing to discover how easy some of these seemingly complicated techniques can be
when explained by someone who knows what it is like to be a beginner.
I read the Apple SKD reference documents for NSTimer and associated reference material, and it seems much more complicated and involved than what you have demonstrated.
This is why web sites like yours are so valuable. It separates the wheat from the chaff so a beginner can grasp the core underlying principle of the subject.
Technical documents are important and necessary but they are no way to learn how to program. They are written by engineers for engineers. Whenever I read the reference documentation from Apple I come away more confused than when I started.
Your tutorials put me on the right track. Thanks again.
nice one…….
tumba chennagide!!!!!!…..
This was simple and to the point! A great help, thanks!
you are master blaster. very good way of elaborating this video.
3 Trackbacks
[...] a couple of ways to make games for the iPhone (eg using the general iphone UI libraries , using opengl es directly, or using a framework), and you should evaluate each way based on your [...]
[...] Animating a Ball Using An NSTimer [...]
[...] tradurre e proporre ai nostri utenti i suoi tutorial e le sue guide. In questo nuovo tutorial, di brandontreb, vedremo come creare una semplice applicazione in cui una palla si muoverà automaticamente e [...]