This is part of an ELC Tech Network

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.

Advertisement

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!

This entry was posted in Interface Builder, Uncategorized, iPhone Programming Tutorials and tagged , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

76 Comments

  1. miah
    Posted February 14, 2009 at 11:12 am | Permalink

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

  2. Posted February 21, 2009 at 10:29 pm | Permalink

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

    Thanks,
    Marv

  3. Posted February 23, 2009 at 4:35 am | Permalink

    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.

  4. iphonenoob
    Posted March 1, 2009 at 10:07 am | Permalink

    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.

  5. simply_muzik
    Posted March 1, 2009 at 7:26 pm | Permalink

    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!

  6. Wolfgang
    Posted March 10, 2009 at 2:53 pm | Permalink

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

  7. Ramon
    Posted March 21, 2009 at 3:40 pm | Permalink

    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.

  8. Posted April 5, 2009 at 10:30 am | Permalink

    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.

  9. rich
    Posted April 29, 2009 at 12:41 pm | Permalink

    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

  10. satish
    Posted May 18, 2009 at 10:41 pm | Permalink

    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?

  11. Sam
    Posted June 5, 2009 at 1:59 pm | Permalink

    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.

  12. Pete
    Posted June 14, 2009 at 6:01 pm | Permalink

    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?

  13. Pete
    Posted June 14, 2009 at 6:02 pm | Permalink

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

  14. Pete
    Posted June 14, 2009 at 6:02 pm | Permalink

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

  15. Matt Mullally
    Posted June 18, 2009 at 8:51 am | Permalink

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

  16. Posted June 18, 2009 at 7:53 pm | Permalink

    Nice tutorial, you make it look easy.

  17. mart
    Posted June 24, 2009 at 4:51 am | Permalink

    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.

  18. preNo0b
    Posted August 18, 2009 at 5:20 pm | Permalink

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

  19. neilio
    Posted October 18, 2009 at 10:05 am | Permalink

    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

  20. Posted November 9, 2009 at 2:45 pm | Permalink

    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!

  21. Posted November 25, 2009 at 6:02 am | Permalink

    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.

  22. Dan
    Posted December 3, 2009 at 7:08 am | Permalink

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

  23. geniexy2132
    Posted January 2, 2010 at 5:01 pm | Permalink

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

  24. Posted January 4, 2010 at 11:06 am | Permalink

    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!

  25. Posted January 8, 2010 at 12:30 pm | Permalink

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

  26. Troy
    Posted January 16, 2010 at 1:30 pm | Permalink

    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!

3 Trackbacks

  1. [...] 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 [...]

  2. [...] Animating a Ball Using An NSTimer [...]

  3. [...] 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 [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">