Welcome to my game programming tutorial on how to create a beginners action game for the iOS. This is a step by step tutorial for creating an iPhone action game. The principles taught also apply to the iPad.
You can see the result of a game running the code in the video below:
The graphics are a bit different with the tutorial (as some of those in the video are being used in an actual project) but that is the result of running the actual code within the tutorial.
Specificially the tutorial features:
- Loading/Placing Images
- Touch Events
- Sound Effects
- Background Music
- Resetting The Game
Pre-requisites For This Game Programming Tutorial
Now before we start there are a few pre-requisites. You should have a basic understanding of Objective-C and will need a Mac with the iPhone SDK installed. The game was created using iPhone SDK 4.0, and the Sparrow Framework. Also note that I created this to be as easy to follow as possible so I used a minimum number of classes/methods to make it as easy as possible for a beginner to follow – I’ve even exclusively used autorelease objects so you don’t need to worry about memory management (one of the facets of Objective-C many beginners have trouble with).
Why Am I Using The Sparrow Framework In This Game Programming Tutorial?
In case you’re wondering why I chose to go the route of using the Sparrow Framework it’s because I believe it is the easiest iPhone game development framework available for free for a beginner to start with, and it has already been used in a number of games in the app store.
Please share this tutorial by tweeting it or sharing using one of the buttons at the bottom.
You can navigate through the tutorial by using the page numbers at the bottom of each page.
If you’d like to jump right in you can download a project with all the resources loaded in here.
Getting The Code
You can download the code using the download links at the end of each page, or you can use the Github project found here:
Otherwise if you’d like to go the route of installing Sparrow, and setting everything up you can visit the Sparrow Framework getting started page here which explains the process of setting up an Xcode project that utilizes the Sparrow Framework. You can get just the game assets (graphics/sound) here.
The tutorial is definitely not perfect, and there are probably some spelling/grammar mistakes, but it is the most extensive single tutorial I’ve seen around and might never be released if I tried to perfect it 🙂
The first thing we’re going to do is start the game scene by displaying in a background image, adding the score and level text, and playing some music. To navigate through this game programming tutorial use the page numbers at bottom, now go to page 2 by clicking that number at the bottom of this article to go to that page.
Displaying The Game Background, Score And Level Text, And Playing Background Music
In this tutorial everything will happen in the Game class files, the Game class extends the Sparrow Stage (SPStage) and
Let’s open up the Game class implementation (game.m) and in the initWithWidth method after the if statement opens we are going to load an image with the line
The reason why I used the imageWIthContentsOfFile: method is because this is the only background image in the game and so I did not need to save the image information as a texture for use elsewhere.
Now we’ll draw the background image to the screen.
Notice that this places the image in the top left corner of the screen which is the (0,0) screen co-ordinate when using the Sparrow Framework, the point in the top left corner is the anchor point for images.
Next we are going to display the score and level text. The first thing we are going to do is declare class wide variables for the score and level in the game.h interface file (place this code inside the squiggly brackets)
We’re also going to declare two SPTextField variables in the interface so that we can update the score and level text throughout the class.
Now getting Back to the Game.m file we are going to initialize the score and level values, create our two text fields and initialize them to contain the score and level values.
Notice that I used textFieldWithText to initialize the text fields and immediately fill them with text. This string of text is immutable, and we will need to change the SPTextField’s text attribute each time we want to update the score and level.
Now we’ll change the text field font, and place them in the upper corners
scoreTextField.x = 160;
scoreTextField.y = 7;
scoreTextField.vAlign = SPVAlignTop;
scoreTextField.hAlign = SPHAlignRight;
scoreTextField.fontSize = 20;
levelTextField.fontName = @"Marker Felt";
levelTextField.x = 0;
levelTextField.y = 7;
levelTextField.vAlign = SPVAlignTop;
levelTextField.fontSize = 20;
The fontName attribute of the text field was used to change the font, and the x and y attributes to place the location of the text field.
I also changed the vertical alignment with vAlign attribute and the horizontal alignment with the hAlign attribute because by default the text receives centered alignment.
Notice that I used the addChild method to add the text fields to the screen.
Now we are going to get the background music playing. The first thing we are going to do is load in the music using the SPSound class.
The reason why we loaded it in like this, and stored it in a variable is because in order to have a sound looping with the sound player we will need to create a channel, we’ll do that with this code:
We’ll now set things up so that the channel loops, turn down the volume a little bit, and start the actual playing.
channel.loop = YES;
channel.volume = 0.25;
If you were to were not retain the SPSoundChannel is that it would stop playing shortly after this init method had finished execution.
Now running the on the iPhone or in the simulator your screen should look like this and music should play:
In the next part of the tutorial we are going to load in the balloon textures and send a balloon upward through the screen.
Loading In The Balloon Textures And Creating Upward Animation
The first thing we are going to do is load in the balloon png files. We’ll add an array variable to the game interface file (Game.h) as we will want to access the balloons from other places within the class.
We’re also going to add in a Sparrow sprite, sprites are display object containers, and we will use this sprite to hold the balloon images so that we can easily stop and reset the game.
Now we’ll head back to the game implementation file and load the textures into the array.
[balloonTextures addObject:[SPTexture textureWithContentsOfFile:@"bluetutorial.png"]];
[balloonTextures addObject:[SPTexture textureWithContentsOfFile:@"greentutorial.png"]];
[balloonTextures addObject:[SPTexture textureWithContentsOfFile:@"indigotutorial.png"]];
[balloonTextures addObject:[SPTexture textureWithContentsOfFile:@"orangetutorial.png"]];
[balloonTextures addObject:[SPTexture textureWithContentsOfFile:@"redtutorial.png"]];
[balloonTextures addObject:[SPTexture textureWithContentsOfFile:@"violettutorial.png"]];
[balloonTextures addObject:[SPTexture textureWithContentsOfFile:@"yellowtutorial.png"]];
Now the reason why i loaded these balloons as SPTexture objects rather than SPImage objects is because I will be using these textures to create images throughout the class, and rather than loading them in each time I can use the texture objects to quickly create images (you’ll see this in a moment).
Now let’s create the sprite for our playing field and add that sprite to the stage.
This sprite will hold the balloons, and content used to reset the game so that we can easily clear the screen and stop animations.
Now we’re going to create a new method and call that addBalloon (make sure to add it to the interface too):
We’re going to use this method to create a balloon and send it upwards. Don’t forget to also declare this method in the Game.h file.
The first thing we are going to do is add in a balloon image of a random color, and place it at a random location below the screen. Place this code in the addBalloon method we just created.
image.x = (arc4random() % (int)(self.width-image.width));
image.y = self.height;
Notice here that i used imageWithTexture to use the texture object. Also you can see that I used the x and y variables of the object to place the image at the desired location, and also used image and height variables which are available in any display object.
In case you are not familiar with the arc4random() function it is a function used to generate random numbers (supposedly providing a greater degree of randomization than the rand() function), and does not need to be seeded.
Now we’re going to send the balloon upwards, and there are two ways to do that one way would be to modify the x and y coordinates of the balloon image directly, but we’ll take the easy way out and use the SPTween class.
time:(double)((arc4random() % 5) + 2)
Notice that I supplied the SPTween class with the image file, how long I wanted the animation to last for (in seconds) and a transition. There are many different transitions available (which can be found in the SPTransitions.h file included with the Sparrow Framework) the linear transition is simply an animation which is done with completely linear timing from start to finish.
Now we’re going to create the actual animation by changing a couple of properties.
[tween animateProperty:@"y" targetValue:-image.height];
All we had to do was change the x and y properties of the image, and the Sparrow Framework modifies these properties over the duration we specified as time when we created the Tween. If you’d like to see the properties available for an image you can check the SPDisplayObject.h file.
Finally we will add this tween to the “juggler”.
The juggler handles the timing for all animations, and is associated with the stage the image we are animating is on.
Now to add a balloon to the stage we are going to add a call to the drawBalloon method at the bottom of the if statement in the initWitWidth method.
You should now see a single balloon rise through the top of the screen when you run the code like in this screenshot:
If you have any trouble you can download a project to bring you up to this point here.
In the next part of this tutorial we are going to make it so that when this balloon is touched it immediately falls through the bottom of the screen.
Adding Touch Events
To program in our response to the balloon being touched we are going to use the Sparrow Framework’s event system. Add this code to the end of the addBalloon method.
There are different SPEvent types, and SP_EVENT_TYPE_TOUCH is run whenever a touchable object is touched.
You can see that we used the selector for a method called “onTouchBalloon” this method will be executed whenever a touch occurs.
We will create the onTouchBalloon method as specified as the event listener, add this into both the Game.h and Game.m files.
Notice that this method takes an SPTouchEvent.
We will need to respond whenever a balloon is first touched, and the first thing we will need to do is determine which object has been touched.
We will remove the touch listener similar to how we added it simply by changing the word add to remove.
We are going to place the following code to increase the score and update the score text.
scoreTextField.text = [NSString stringWithFormat:@"Score: %d", score];
We’re also going to play a popping sound.
Notice that all I did here was execute the play method on the SPSound. We don’t need to do any more here as we don’t need to loop or change the volume as we did with the background music. This is the simplest way to play a sound using the Sparrow Framework.
Let’s stop the upward animation of the balloon by removing all animations related to the touched balloon from the Juggler.
Now we’re going to change the scale of the balloon to give the balloon a thinning effect like the air is flowing out from it.
[tween animateProperty:@"scaleX" targetValue:0.75];
[tween animateProperty:@"scaleY" targetValue:1.25];
Notice that I changed the scale of the balloon by adjusting the scaleX and scaleY properties.
Now we’re going to send the balloon out through the bottom of the screen.
[tween animateProperty:@"y" targetValue:self.height+currentBalloon.height];
If everything is done right when the project is run a single balloon should be sent up the screen, and fall through the bottom of the screen when touched like in this screenshot:
If you have any problems you can download a project file to bring you to this point here.
In the next section we are going to draw more balloons as they are popped and increase the score and level.
Triggering Events From Other Events
The first thing we are going to do is create a simple method with a for-loop to create more balloons as the level goes up. Add the code below into the Game.m file, and declare the method in the Game.h file.
for(int i = 0; i < level; i++)
Now we’re going to add an event listener (similar to what we did with touches) so that we can execute some code when the balloon has exited the screen. Place this code at the bottom of the addBalloon method.
Noticed that I added this event listener to the tween variable that we created for the balloon’s rising animation. The tween completed event occurs when this animation completes and with this code the movementThroughTopOfScreen method will be executed.
Now we’re going to create the movementThroughTopOfScreen method, and make it so that the animation stops. Add the following code into the Game.m file, and declare the movementThroughTopOfScreen method in the Game.h file.
Executing the removeAllObjects method on the juggler ends the execution of the tween’s that we created.
Now we’re going to add another listener this time to the end of the onTouchBalloon method.
We’re going to create the method for this listener now that executes when the balloon has completely fallen through the screen. This is the method header to add to the Game class files.
We’re going to need to remove the balloon from the playfield so just as we did in the ontouchballon event we’re going to get the target only this time cast it is a tween so we’re going to need to cast it as such, and get the target of the tween which is the balloon, and what we really want.
SPDisplayObject *currentBalloon = (SPDisplayObject*)[animation target];
We’re going to remove the balloon completely from the playing field.
Now if all balloons have been removed we need to increase the level, and send out more balloons onto the playing field. This is the code we’ll use to do that.
The numChildren variable as you can probably guess tells us how many children a sprite has.
The rest of the code on this page will go within this if statement.
Let’s increase the level, and update the display.
levelTextField.text = [NSString stringWithFormat:@"Level: %d", level];
Now to start up the next level we are going to execute the drawBalloons method.
Now when we run the project as we pop balloons more will show up, and if one exits through the top of the screen the game will pause.
This screenshot shows how multiple balloons should appear on the screen once you start popping balloons:
In the next part of the tutorial we’re going to add a reset button, and restart the game so we can keep playing.
Resetting The Game
The first thing we are do here is add a classwide boolean variable so that this code will not execute multiple times so place this code in the interface in the Game.h file.
The reason I added this was because if multiple balloons exit the screen at the same time the movementThroughTopOfScreen method is executed multiple times.
Now add this if statement into the movementThroughTopOfScreen method.
resetButtonVisible = YES;
The reason I added this was because if multiple balloons exit the screen at the same time the movementThroughTopOfScreen method is executed multiple times.
Now we’re going to add a semi-transparent image covering the screen.
An added side effect of running this code is that touches are prevented from reaching any ballons.
Now we’re going to add a button to the center of the screen.
resetButton.x = self.width/2-resetButton.width/2;
resetButton.y = self.height/2-resetButton.height/2;
resetButton.fontName = @"Marker Felt";
resetButton.fontSize = 20;
resetButton.text = @"Reset Game";
Notice that in creating this button we needed to provide an image, however the animation causing the image to shrink is all built in to the Sparrow Framework. As you can see the properties of buttons are very similar to text fields.
Now we’re going to add an event listener to the button.
The triggered event occurs when the button is pressed.
Add the button to the playing field with this code:
Now we’re going to create the onResetButtonTriggered event which runs when the button is pressed.
This method is pretty simple we just clear the screen, and then make things just as they were when the game first started.
And that’s the end, when you run this tutorial you should see a reset button and be able to restart the game after a ballon exits through the top of the screen like in the screenshot below:
I hope you enjoyed this tutorial please re-tweet and share it by using the buttons below. If you have any questions then please enter them in the comments below. I’d also love to here what you’d like to see next with this (menu, highscores, powerups?). Thanks.