iPhone Programming Tutorial - Animating a Ball Using An NSTimer
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!
- Posted on 28 Oct 2008 in Interface Builder, Uncategorized, iPhone Programming Tutorials
- Digg |
- Del.icio.us |
- Stumble |
44 Responses
Brian Says:
October 28th, 2008 at 1:12 pm
Brandon - I am really looking forward to the series on game programming. I would be willing to donate some money to help expedite the tutorials. I know you are probably busy but it would be cool if you set up a system where if $X were donated you would have the tutorial up by Y date, otherwise it would be posted when you have free time.
From reading all of your posts about advertising and keeping things fair, I trust that you wouldn’t withhold tutorials until the donation goal is met. What are your thoughts?
Joe Says:
October 28th, 2008 at 5:40 pm
Nice! That was very well explained. Thanks for simplifying this.
benjbrown Says:
October 28th, 2008 at 8:43 pm
Good job, I was just wondering about this and the vid tutorials make it clearer then reading Aarons book concerning timers.
Niklas Says:
October 29th, 2008 at 3:55 am
Brandon, I can’t say how much I enjoy (and crave) for these tutorials. By far the best iPhone tutorials and the best site.
I wish you the best, I will start donating some money soon and when I start making iPhones app for the company I work on I will make sure they donate as well.
If you need any help, post it on in blog post and I am sure many viewers (my self included) will do anything in our power to help you. You’r that good.
Regards,
Niklas
jazzmic Says:
October 29th, 2008 at 4:28 am
Hi, great tutorial. I’m very interested in games, and for once I feel I’m a litle ahead, but I will be following with a lot of interest your next upadates.
The only thing I would like to comment is that at least in games, I find it not very useful to use IB, as items are loaded and removed all of the time (at least in the games I’m working on), so I prefer doing things just by code. But I still have many things to learn, so as I said, I’ll keep checking back!
Keep up the good work!
Mark Buckingham Says:
October 29th, 2008 at 12:48 pm
I’m really interested in all of this too. I guess what I’m wondering, is how much can you possibly do this way? (Because I’d love to avoid OpenGL just yet).
In other words… Can you pull off something as complex as an asteroids clone?
Brandon Says:
October 29th, 2008 at 1:24 pm
@Mark,
Yes, you could pull off an asteroids clone. It is actually quite simple coding a game this way. You probably couldn’t do any 3D stuff this way… but for sprite-based games it’s fine.
@Brian
I would not be opposed to this. I would love to push the tutorials out faster, I just have quite a bit of school and work. I would be willing to leave work early if that income were to be supplemented…What did you have in mind?
I would never ‘withhold’ tutorials until a goal is met. I love posting new tutorials and usually can’t wait until I can post the next one. So this wouldn’t be an issue.
@ Everyone
Do any of you guys have any ideas for a game tutorial series your would like to see. I was thinking table tennis or some asteroids port. It must be simple enough to cram into 3-4 part series but complex enough to teach a lot of functionality. I would like to include:
- Graphics movement/animation
- Sound
- Accelerometer
- Possible multitouch (table tennis could be multiplayer)
- Splash Screen/Main Menu
So if you have any ideas, please post them here.
Thanks…
Brian Says:
October 29th, 2008 at 2:16 pm
Brandon - How long does a tutorial take you from start to finish? Let’s say 3 hours. I have no idea what your job is or how much you get paid but if you’re in college like myself lets say $10/hour. So when $30 (3 x $10 = $30) is donated you can take off work early and do the tutorial instead. The donations are accumulated until the goal is reached.
For example let’s say $25 is donated on Monday and on Tuesday you post the next tutorial on your free time. On Wednesday $10 is donated bring the total to $35, so you take off work and post the tutorial. The next donation pool starts at $5 ($35 - $30 = $5) and you continue posting tutorials during your free time until the goal is hit again.
What are everybody’s thoughts about this?
Obviously there won’t be a strict schedule that we are going to hold you to. The point is to see a direct relationship between donations and more tutorials. Hopefully this will be provide some sort of structure instead of arbitrarily donating money and hoping that it will inspire you to post more tutorials.
As for the game, I think asteroids would be really cool. Honestly I’d be happy with any game.
I’m a web developer so feel free to email me if you need any help setting it up.
Brandon Says:
October 29th, 2008 at 2:32 pm
@Brian,
This could work…I would say 3 hours is a fair amount of time to complete a tutorial. I currently intern at Intel and get $25/hour. So it might get a little pricey, but if you guys are willing, I am too.
I work all day this Friday, so if $75.00 can be donated by Friday, I will leave work early and complete the first tutorial in the series. If not, no biggie, the first tutorial would then come out sometime Monday or Tuesday…
Let me know what you think…
Stubb Says:
October 30th, 2008 at 10:54 am
Another idea would be to try and run some kind of web conference or demo. The video you have there is awesome, it would be interesting if you were to do another one “live” (after a few dry runs, of course). You could have a $25 sign-up fee for each student.
If you take a look at some of the web conferencing options out there they are reasonably priced. At http://www.webtrain.com/web-conferencing-pricing.asp you can see that you could host an unlimited number of 20 person meetings for $99 a month. At $25 a head you’d clear $376 per session.
Just an idea, I haven’t done any research beyond that link but it might be worth it. And I’d be happy to lend a hand getting it running (maybe in exchange for a reserved slot??)
Mike Says:
October 30th, 2008 at 11:38 am
Brandon, love the tutorials. I’ve learned more here than i have been able to from any other source. Btw, i like the video tutorials, but i kind of miss the very detailed write ups. I’m coming at this from a web designer/actionscripter so the knowing ‘why’ I’m doing something really helps. I will definitely donate what I can. Anyway, in terms of the game.. i can’t wait. I really want to learn about simple animation (i agree with mark, open gl is probably beyond my reach right now). But i want to see what can be done with the other systems. 2d is fine. I really want to see how to animate objects. In the example of the asteroids game… it has a primary shape, but once it hits an asteroid, explodes. I am so used to a timeline and visual animation. this is all new to me. Anyway, great work!
jazzmic Says:
November 1st, 2008 at 5:38 am
Well, I don’t really like the idea of paying for the tutorial. I’ve seen other sites do it and what happens is that not that many people pay for this, so they are forced to make more general purpose tutorials so more people get to pay, and at the end, they become like the rest…
Still, if you did a tutorial on something that mattered to me, I would pay.
As of tutorial sugestions,after the comments I’ve just made, mayber they are out of place, but here they go:
I’m very interested in a game that loads and removes items all the time, how would the memory management be solved. I’ve been doing some tests and I feel I have memory leaks everywhere… Asteroids is fine for me.
Sound would be excellent as well, it’s very complicated, specially if you want background music and special effects on the top.
The last thing I would like to learn is how to connect to an online server, to save high scores and maybe some multiplayer (or at least chat). This last request I guess is very hard, but well, it’s an idea.
AV Says:
November 1st, 2008 at 8:22 am
HI
Your tutorials are really helpful! Could you post some examples (or email me) on how to move a button around the screen while other buttons get reorganized …something like moving the applications on the iphone home screen.
Thanks
eric Says:
November 2nd, 2008 at 8:26 pm
OK this is good stuff. Really good. So good I am donating $7. I hope that others that are benefiting from this site will donate a little as well to insure speedy development of more tutorials. And Im glad to see they are heading toward a game oriented theme.
I’ve run through various tutorials ( Apples, etc ) and these are the best. The extreme simplicity of each individual project really helps. Coming from a non Mac, non objective c, and having to learn Xcode, Interface builder, etc as well, the learning curve for me has been rough. this blog has assisted me tremendously.
Brandon keep up the good work!
Christopher Kalanderopoulos Says:
November 2nd, 2008 at 8:45 pm
Hello Brandon,
How can we get in contact with you personally to discuss business and iPhone programming that should be kept private (for obvious reasons)?
Could you provide a personal email or form to fill out if you do not want spam bots seeing your email all over the web? Thanks so much.
Will Says:
November 3rd, 2008 at 2:26 am
Hello Brandon,
I was wondering if you could also put your videos up in a format that is viewable on the iPhone’s browser. This way I could view your AWESOME tutorials away from the computer.
If not that… maybe provide a link to download the video file so that i could put them onto my iPhone.
Thanks so much for the tutorials, I have learned a lot from you and you should see an app coming from me on the app store pretty soon thanks to your help with some of my questions.
Brandon Says:
November 3rd, 2008 at 8:19 am
@Christopher
My email is brandon [at] icodeblog [dot] com.
@Will
I will do this eventually, at them moment I am so swamped, I don’t have time to do all of the conversions. I will try to do it sometime next month (after school is out).
Thanks for being a part of the site.
Brandon Says:
November 3rd, 2008 at 8:21 am
@ Stubb
That’s a good idea, but I think it will be hard to get 20 people together that want to pay for such a session.
I will consider this in the future and if it happens, you can have a free spot…
Mark Says:
November 4th, 2008 at 5:08 am
Nice videos. It is so much better when someone guides you through something by words and moving pictures.
What screencasting tool are you using? Those videos had great quality.
Scott Says:
November 5th, 2008 at 7:31 am
As always, a very clear and easy to understand example….but looking forward to some openGL tutorials too!
Many thanks.
Tobi Says:
November 5th, 2008 at 7:49 am
@ Brandon
My idea is the following:
Instead of the ball we use a button with a picture… the botton is changing randomly the position on screen, so you have to catch/press him. The button will run faster and faster on counting points.
Daniel Says:
November 5th, 2008 at 11:26 pm
The thing I don’t like about your tutorials is that you don’t always explain why you do what you do, which makes it very hard to truely learn anything. For instance you said “Ket’s synthesize this” and put the synthesize command….Why? when would I need to do this in the future? what is this command for? I just think that things like that should be explained more in depth instead of just telling us what to type where.
Brandon Says:
November 6th, 2008 at 12:19 am
@Daniel,
I assume in each tutorial that you followed all of my previous tutorials up until this point. In previous tutorial, I went over why you would synthesize properties.
I can’t explain why you do this in every tutorial or they would get too long and I would get sick of doing them really fast.
Thanks for your input…
RSD Says:
November 6th, 2008 at 1:40 am
How would you to multiple balls where the number of balls in not known ahead of time. So let’s say we start with one ball, add 2 more, then 5 more, then remove 2, add 7 etc…. There may be as many as 100 balls at one time different colors but same behavior - run into wall and bounce.
punk84 Says:
November 8th, 2008 at 1:41 pm
Great and use-full tutorial for novice iphone developers like me ! !
Thank you!
Shoaib Says:
November 9th, 2008 at 8:14 am
Very great Tutorial. I appreciate your great efforts and you are real man that is helping others to come on iPhone Platform. It helps me a lot.
Thanks man. Keep continue
Pierre Says:
November 13th, 2008 at 10:09 am
Hello.
I’m french developer and I’m starting on iPhone device.
Great tutorials !
Keep this way .
Mitch Says:
November 20th, 2008 at 3:46 pm
Great tutorial. What software are you using to record the screen?
maw Says:
November 21st, 2008 at 6:46 am
I am just another iPhone-dev-newbie who can’t wait for further tutorials, especially for a simple game in an OGLES view. I find it so hard to start something like this on my own, because I dont know where to start.
Or maybe someone knows other sites with such tutorials? Very much appreciated.
Thanks!
iPhone @ travio » Blog Archive » Game development.. getting started Says:
December 10th, 2008 at 1:30 am
[...] 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 [...]
Nick Shannon Says:
December 15th, 2008 at 10:28 pm
Dear Brandon,
I’m a 12 year old kid who has lust to create great apps. Your tutorials have been helping me create small things, but I have no backround in programming. Do you have any recourses where I can learn programming terms? Also when I try drag new refrencing outlet to files owner all it says is view. Could respond asap.
thanks
-Nick
wren Says:
December 18th, 2008 at 3:25 am
nick, make sure your viewcontroller source files are saved before you open the xib file…
Ricardo Barroso Says:
December 22nd, 2008 at 6:54 pm
First of all, congratulations!!
Very, very nice, easy and motivating tutorial!!
I would like to point just a minor detail which can be useful for someone who try this tutorial.
Before going to the Interface Builder, you should save the changes on Xcode. If not, when you’ll try to connect the “UIImageView” to the “ball” variable, you’ll not see the “ball” description to terminate the link!
Brandon, I’ll certainly do some more of your tutorials, excellent!!
Thanks,
Ricardo
Ricardo Barroso Says:
December 22nd, 2008 at 6:59 pm
Oh… sorry, I didin’t read all comments and just now aftear submint my comment, I’ve read that the wren response to Nick Shannon, is exactly about that! Sorry for the repetition!
Ricardo
Kieran Says:
December 23rd, 2008 at 11:04 pm
Brandon great job! These tutorials r amazing, very easy to follow and have been alot easier to understand than the apple documentation.
I agree with previous posters about doing a 2d game series. Perhaps u could use quartz 2d(not openGL plz haha) andas a start show how to make this ball program programmatically? And use quartz drawing functions to actually draw the ball? Then add obstacles or multiple balls and a control like a button to add more balls! Then maybe use the acceleromater data to steer the balls?ur call :). Keep it up!
Donna Says:
January 1st, 2009 at 3:18 pm
Would it be possible to move the ball around directly… instead of putting in a VIEW?
Tom R Says:
January 1st, 2009 at 3:20 pm
What does that default line in did-view-load{} actually do… [super something]?
It’s ok to keep… or remove it?
Ricardo Barroso Says:
January 1st, 2009 at 5:44 pm
Tom R, the default line:
[super viewDidLoad];
calls the superclass “viewDidLoad” method.
Since in this case the superclass is the “UIViewController” which I suppose doesn’t do nothing, there is no problem in removing that line.
Ricardo
Mark Says:
January 2nd, 2009 at 8:37 am
Very nice tutorial. Thank you very much!
I was wondering thou, how can you determine the size of the image on the screen so it doesn’t look at the center point but really the edges of the ball.
Like in pseudo code I would mean:
if (ball.center.x - (ball.width / 2) > 320) {
reverse x speed
}
Rob Says:
January 4th, 2009 at 1:14 am
Hey Mark,
I’m just learning as well, coming from c#.
I thought the exact same thing and and added this:
float w = ball.bounds.size.width/2;
float h = ball.bounds.size.height/2;
i then edited the if statements to subtract the w from the x, and the h from the y.
Tylor Says:
January 4th, 2009 at 12:02 pm
Hey,
I would love to see a simple Mario type game. Even if it was just walking back and fourth on a brick wall. Of course jumping on enemies and stuff would be cool but I have no idea on how complex that is. Just my suggestion. Thanks for the site! Keep up the great work!
James Says:
January 5th, 2009 at 10:28 pm
Great tutorial! The only problem I had was when i tried to connect the ball to the File Owner, I only go the option view not ball. This prevented me from continuing making the app.



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.