7/30/2009

iPhone Game Tutorial (Part 1)

I thought I could share my methods on how I animate and move stuff around on the iPhone for games with you.
As always, these are just my ways of doing it. I'm sure there are better ways but I'm also very sure that there are far worse ways as well.



First comes first:
What do we want to make this app do ?
As a starter I thought it would be cool having a little man being able to run across the screen in an animated fashion.
You'll need the sprites and the background so it looks nicer.

Sprites


Once downloaded we can move on.

Create the Project:
Easy enough. Create a View Based Application. Give it a name and move to the viewController.h.

ViewController.h:
We will need to add a few things here.
Our project is going to need a UIImageView to display our little soldier.
We are also going to need an array to hold our images for the walking animation.
For the movement I like using a timer, so we'll create that too.

As for the functions, we're going to use a button to make the little guy walk across the screen of our iPhone.
So we'll create two functions for that. The name explains itself, right?
The other two void functions will be used by the timer.
@interface AnimateViewController : UIViewController {
UIImageView *player;
NSArray *walkImages;
NSTimer *walkingTimer;
}

-(IBAction)walk;
-(IBAction)stopWalking;
-(void)startMovingForward;
-(void)moveForward;

Moving on the ViewController.m:
First we're going to create our little world for the little guy to walk around on.

Make the application load in Landscape mode

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return (interfaceOrientation == UIInterfaceOrientationLandscapeLeft);
}

Interface Builder:
Now open the ViewController.xib and click on the gray arrow in the top corner of the view. This will make the view rotate into landscape. Add a UIImageView, have it take the whole screen and display "wof028.png" in it and set the mode to aspect fit.
Don't forget to add a UIButton in the top right corner to make the soldier walk.
Go to the Button Connections and assign the function "Walk" to "Touch Down" and "StopWalking" to "Touch Up Inside".
Save and close the Interface Builder.

Back to .m:
Insert the following in the viewDidLoad:
- (void)viewDidLoad {
[super viewDidLoad];

walkImages = [[NSArray alloc] initWithObjects:
[UIImage imageNamed:@"w1.png"], [UIImage imageNamed:@"w2.png"],
[UIImage imageNamed:@"w3.png"], [UIImage imageNamed:@"w4.png"],
[UIImage imageNamed:@"w5.png"], [UIImage imageNamed:@"w6.png"], nil];

player = [[UIImageView alloc] initWithFrame:CGRectMake(100, 220, 30, 30)];
player.image = [UIImage imageNamed:@"stand.png"];
player.animationDuration = 1.5;
player.contentMode = UIViewContentModeBottomLeft;
[self.view addSubview:player];

}

Here we simply assigned the images to the array. We could do it with a loop too (which is recommendable if you have more than just a few files) but for this example I wanted to show it like this to make it clearer.

We also initiate our ImageView "player" with a frame (CGRect). A frame is just that. A frame that holds the position of our image. Much like a picture frame in real life. If you don't understand the numbers of CGRectMake try altering them and see what happens.
We also assign a standard "standing" pose with the "stand.png" to the player.

The animation duration number is the number of seconds it need to cycle through the whole animation. You'll need to try and see what works good for you. For this example I use 1.5.

The ContentMode sets where the images will be placed every time in the frame. This is important when the sprites are of different sizes. In our case, not so much.

Last, we add the image to our view.

Taking care of the rest:
Add the following:

#pragma mark -
#pragma mark IB Actions

-(IBAction)walk {
[self startMovingForward];
player.animationImages = walkImages;
[player startAnimating];
}

-(IBAction)stopWalking {
[player stopAnimating];
[walkingTimer invalidate];
}

#pragma mark Move it

-(void)startMovingForward {
walkingTimer = [NSTimer scheduledTimerWithTimeInterval:0.125 target:self selector:@selector(moveForward) userInfo:nil repeats:YES];
}

-(void)moveForward {
player.frame = CGRectMake(((player.frame.origin.x)+5), 220, 30, 30);
}

Pragma Mark ??
Pragma Mark can help you organize your code for when it gets very long. Copy the code above and then click on the two arrows pointing up and down at the top back above your code. This will open an index of your methods and the pragma mark text will help you find what you need.

When we tap on the button we'll start the "walk" function. The walk function starts the "moveForward" function, assigns the array walkImages to the property animationImages of our player ImageView and tells the program to start Animating "player".

startMovingForward will just start the timer. We give it an interval to work with and in the selector we tell it to activate "moveForward" on every interval. Don't forget to tell the timer to repeat itself.

moveForward will finally take care of the actual moving of the little soldier. We assign a new frame to player which is the same as the current one but we add 5 pixel to its x axis.

When we lift our finger from the Walking button, the animation and the timer will be stopped.

Build and run the application. See how it goes.
Reblog this post [with Zemanta]

6 comments:

  1. This is great!1 Can you post the Void code for each movement? I kinda got lost there...Cant wait for the next one!!

    ReplyDelete
  2. The code is all there. To move your sprite, look at the two methods at "#Pragma Mark Move it".

    ReplyDelete
  3. Very cool! This is a great way to start programming games.... You made me think hard about gaming now! THANKS!!

    ReplyDelete
  4. This' great!!! It helped me a lot...! Thank you!

    ReplyDelete
  5. This looks great - are the sprites still available so I can follow?

    ReplyDelete
  6. Unfortunately not but you can really just use any other sprites for the example.

    ReplyDelete