iPhone Programming Tutorial – Animating a Ball Using An NSTimer

October 28th, 2008 Posted by: (ELC) - posted under:Tutorials

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!

  • Brian

    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?

  • Samuel

    I totally agree with the donating idea of Brian.

  • Joe

    Nice! That was very well explained. Thanks for simplifying this.

  • benjbrown

    Good job, I was just wondering about this and the vid tutorials make it clearer then reading Aarons book concerning timers.

  • http://www.bivald.com Niklas

    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

    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

    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?

  • http://www.icodeblog.com Brandon

    @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

    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.

  • http://www.icodeblog.com Brandon

    @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

    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

    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

    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

    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

    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

    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

    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.

  • http://www.icodeblog.com Brandon

    @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.

  • http://www.icodeblog.com Brandon

    @ 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

    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

    As always, a very clear and easy to understand example….but looking forward to some openGL tutorials too!
    Many thanks.

  • Tobi

    @ 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.

  • http://amdiphonedev.blogspot.com Daniel

    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.

  • http://www.icodeblog.com Brandon

    @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…

  • http://RSD@gmail.com RSD

    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

    Great and use-full tutorial for novice iphone developers like me ! ! :)

    Thank you!

  • Shoaib

    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

  • http://www.ceetix.fr Pierre

    Hello.

    I’m french developer and I’m starting on iPhone device.
    Great tutorials !
    Keep this way .

  • http://www.mitchallen.com Mitch

    Great tutorial. What software are you using to record the screen?

  • maw

    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!

  • Pingback: iPhone @ travio » Blog Archive » Game development.. getting started

  • Nick Shannon

    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

  • http://www.bangme.net wren

    nick, make sure your viewcontroller source files are saved before you open the xib file…

  • http://xphone.me/ Ricardo Barroso

    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

  • http://xphone.me/ Ricardo Barroso

    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

  • http://xphone.me/ Ricardo Barroso

    Errata:
    aftear => after
    submint => submit

  • http://N/A Kieran

    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

    Would it be possible to move the ball around directly… instead of putting in a VIEW?

  • Tom R

    What does that default line in did-view-load{} actually do… [super something]?

    It’s ok to keep… or remove it?

  • http://xphone.me/ Ricardo Barroso

    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

    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

    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

    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

    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.

  • James

    Nevermind, I found the problem.

    Hey, is there a source code for changing the look of the status bar in an app?

  • Pavel

    Brandon, thanks for the tutorial. Something is bugging me though. I followed all the steps and in the Interface Builder my background is black, but when I run in the Simulator it’s white. Any ideas why?

  • http://weblogs.thekeunster.com Keun Lee

    Hey Brandon, quick question. What did you use for desktop capturing your video tutorial?

  • Cp

    When I try this, I get the black background, and there are no errors, but there is no ball. I had the same problem with the UITouch tutorial….am I doing something wrong?

  • James

    This tutorial helped me off to a great start with programming. Thank you very much for taking the time to make and upload this video.

  • James

    Hey thank you for taking the time to make and upload this video, it gave me a great start to coding for the Iphone and Ipod touch.

  • Kahoonas

    Thanks so much for this tutorial. Just in case you’re needing ideas for future tutorials I would love one on creating a game which involves a sprite ‘falling’ through a level of some kind. I suppose like a rolling ball maze game but utilizing the accelerometer to make the ball fall downwards.

  • miah

    Thanks for the tutorial. It is the first one that has been a success so far.

  • http://carsalesassistant.com Marv Chomer

    Is there any way to make a copy of a graphic–kinda like tiling? Lets say you wanted 15 balls flying around…

    Thanks,
    Marv

    • Corwin

      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

  • http://xnanoob.exteen.com xnanoob

    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.

  • iphonenoob

    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.

  • simply_muzik

    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!

  • Wolfgang

    Thank you very much for your work. Very appreciated. Great tutorials!

  • Ramon

    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.

  • http://www.solvengineer.com Mike

    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.

  • Pingback: 精彩生活 » 博客文章 » iPhone编程资源站

  • rich

    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

  • satish

    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?

  • Sam

    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.

  • Pete

    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?

  • Pete

    DOH!!! Should have looked directly above…. sorry

  • Pete

    DOH!!! Should have looked directly above…. sorry

  • Matt Mullally

    Excellent job Brandon, just starting iphone development and your tutorials are fantastic. Thanks for taking the time and effort to put them in.

  • http://www.cannla.com Marshall

    Nice tutorial, you make it look easy.

  • mart

    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.

  • preNo0b

    Excellent tutoial! How would i go about making the ball react to touch? as in the ball bounces off the area touched.

  • neilio

    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

  • http://empowereddesignapps.tk Michael

    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!

  • http://www.daftninja.co.uk Pete

    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.

  • Dan

    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!!

  • geniexy2132

    can you programatically add the image of the ball instead of adding it through interface builder?

  • http://twitter.com/northstreamer Northstreamer

    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!

  • http://www.kdp-tech.com Keyur Patel

    @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.

  • Troy

    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!

  • Pingback: T#026 – Creiamo un’Animazione di una Palla con un NSTimer (by iCodeBlog) | devAPP

  • Lin

    Memory leaks…

  • Shubhojit

    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.

  • http://ezinearticles.com/?La-Martina-Reaches-Peak-Sales-in-2010-Q1&id=3895722 la martina

    I organize this collection to be unequivocally useful. I am using it in a report I am article at college.

    la martina

  • Ham

    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];
    }

  • David

    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.

  • akash

    nice one…….

  • nataraj

    tumba chennagide!!!!!!…..

  • Ben

    This was simple and to the point! A great help, thanks!

  • Ashish

    you are master blaster. very good way of elaborating this video.

  • Pingback: » Blog Archive » 10家不错的iphone编程资源站

  • Don

    A useful animation library for iOS:

    http://www.modejong.com/AVAnimator/

canakkale canakkale canakkale balik tutma search canakkale vergi mevzuati bagimsiz denetim vergi mevzuati ozurlu engelliler