2011年12月18日星期日

How To Make A Multi-directional Scrolling Shooter Part 2

How To Make A Multi-directional Scrolling Shooter Part 2:
Learn how to make a multi-scrolling tank shooting game!
Learn how to make a multi-scrolling tank shooting game!

This is a multi-part tutorial series where we show you how to make a cool multi-directional tank battle game for the iPhone.

In the first part of the series, we created a new Cocos2D 2.0 project with ARC support, added our tile map into the game, and added a tank we could move around with the accelerometer.

In this second and final part of the tutorial, we will make our tank shoot bullets, add enemy tanks, add some win/lose logic, and add some polish and finishing touches.

This project begins where we left off last time, so grab the project where we left it off last time if you don’t have it already.

So, shall we make a game?



Running and Gunning


Right now our tank can move, but he can’t shoot! Since shooting is to tanks as buying shoes is to my lovely wife, we better fix this ASAP ;]

We already made it so that the tank moves with the accelerometer, so we’re all free to make the tank shoot wherever the user taps. However, to make the game more fun, instead of just shooting once when the user taps, we’ll make the tank shoot continously!

So let’s modify our Tank class to add some methods for shooting. Make the following changes to Tank.h:


// Add inside @interface
CGPoint _shootVector;
double _timeSinceLastShot;
CCSprite * _turret;

// Add after @interface
@property (assign) BOOL shooting;
- (void)shootToward:(CGPoint)targetPosition;
- (void)shootNow;


Here we add an instance variable to keep track of the direction we’re shooting in, and how long it’s been since the last shot. We also keep track of a new sprite we’ll be adding on top of the tank – the tank’s turret!

Next open Tank.m and make the following changes:


// Add to top of file
#import "SimpleAudioEngine.h"

// Add right after @implementation
@synthesize shooting = _shooting;

// Add inside initWithLayer:type:hp
NSString *turretName = [NSString stringWithFormat:@"tank%d_turret.png", type];
_turret = [CCSprite spriteWithSpriteFrameName:turretName];
_turret.anchorPoint = ccp(0.5, 0.25);
_turret.position = ccp(self.contentSize.width/2, self.contentSize.height/2);
[self addChild:_turret];


Firt we synthesize our variables. Next we create a new sprite for the tank’s turret, and add it as a child of the tank. This is so that when we move the tank sprite, the turret moves along with it.

Note how we position the turret:

  • We modify the anchor point to be pretty close to the base of the turret. Why? Because whatever the anchor point is set to is the point where rotation is around, and we want the turret to rotate around its base.
  • We then set the position of the sprite to be the center of the tank. Since this sprite is a child of the tank, it’s position is relative to the bottom left corner of the tank. So we’re “pinning” the anchor point (the base of the turret) to around the middle of the tank.

Next add a new method to the bottom of the file:


- (void)shootToward:(CGPoint)targetPosition {

CGPoint offset = ccpSub(targetPosition, self.position);
float MIN_OFFSET = 10;
if (ccpLength(offset) < MIN_OFFSET) return;

_shootVector = ccpNormalize(offset);

}


We’ll call this method when the user taps a spot. We check to make sure the spot tapped is at least 10 points from the current position first (if it’s too close, it’s hard to tell where the user really wants to shoot). Then we normalize the vector (remember, this makes a vector of length one) so we have a vector in the direction we want to shoot in, and store that for future reference.

Add the method to actually shoot next:


- (void)shootNow {
// 1
CGFloat angle = ccpToAngle(_shootVector);
_turret.rotation = (-1 * CC_RADIANS_TO_DEGREES(angle)) + 90;

// 2
float mapMax = MAX([_layer tileMapWidth], [_layer tileMapHeight]);
CGPoint actualVector = ccpMult(_shootVector, mapMax); 

// 3
float POINTS_PER_SECOND = 300;
float duration = mapMax / POINTS_PER_SECOND;

// 4
NSString * shootSound = [NSString stringWithFormat:@"tank%dShoot.wav", _type];
[[SimpleAudioEngine sharedEngine] playEffect:shootSound];

// 5
NSString *bulletName = [NSString stringWithFormat:@"tank%d_bullet.png", _type];
CCSprite * bullet = [CCSprite spriteWithSpriteFrameName:bulletName];
bullet.tag = _type;
bullet.position = ccpAdd(self.position, ccpMult(_shootVector, _turret.contentSize.height));       
CCMoveBy * move = [CCMoveBy actionWithDuration:duration position:actualVector];
CCCallBlockN * call = [CCCallBlockN actionWithBlock:^(CCNode *node) {
[node removeFromParentAndCleanup:YES];
}];
[bullet runAction:[CCSequence actions:move, call, nil]];
[_layer.batchNode addChild:bullet];
}


There’s a bunch of code here so let’s go over it bit by bit.

  1. First we rotate the turret to face in the direction we want to shoot. There’s a handy function called ccpToAngle we can use that takes a vector and returns the angle of the vector in radians. We then convert this to degrees (which Cocos2D uses), multiply it by -1 because Cocos2D uses clockwise rotation. We also add on 90, which we need to do because our turret artwork is facing upwards (instead of to the right).
  2. Next we figure out how far we want to shoot the bullet. We basically want to shoot it a long way, so we get the max of the tile map’s width or height and multiply it by the direction we want to shoot.
  3. Next we figure out how long it should take the bullet to get to that spot. This is simple – we divide the length of the vector (the max of the tile map’s width or height) and divide it by the points per second we want the bullet to move.
  4. Gratuitous shooting sound effect! :]
  5. Finally we create a new bullet sprite, run an action on it to make it move (and disappear when it’s done moving) and add it to the layer’s batch node.

Next make these changes to Tank.m:


// Add new methods
- (BOOL)shouldShoot {

if (!self.shooting) return NO;   

double SECS_BETWEEN_SHOTS = 0.25;
if (_timeSinceLastShot > SECS_BETWEEN_SHOTS) {       
_timeSinceLastShot = 0;
return YES;       
} else {
return NO;
}
}

- (void)updateShoot:(ccTime)dt {

_timeSinceLastShot += dt;
if ([self shouldShoot]) {      
[self shootNow];       
}

}

// Add inside update
[self updateShoot:dt];


This is the code we need to make the tanks shoot continuosly. Every update loop we’ll call updateShoot. This just checks if it’s been at least 0.25 seconds since the last shot, and calls shootNow if so.

OK, finally done with Tank.m! Let’s try this out. Open up HelloWorldLayer.m, and replace ccTouchesBegan and ccTouchesMoved with the following:


- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

UITouch * touch = [touches anyObject];
CGPoint mapLocation = [_tileMap convertTouchToNodeSpace:touch];

self.tank.shooting = YES;
[self.tank shootToward:mapLocation];  

}

- (void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {

UITouch * touch = [touches anyObject];
CGPoint mapLocation = [_tileMap convertTouchToNodeSpace:touch];

self.tank.shooting = YES;
[self.tank shootToward:mapLocation];  

}


So basically, we’re using taps to shoot now instead of move.

Build and run, and now you can tap the screen to unleash a hail of bullets! Mwuahaha, the power!

Tank shooting bullets in all directions

Note that the way we’re shooting bullets here really isn’t the best because we’re continously allocating bullets, and allocations are expensive on iOS. A better way is to preallocate an array of bullets, and re-use old bullets from the array when you want to shoot one. We cover how to do this in the Space Game Starter Kit.

Adding Some Enemies


We can’t have a tank game without enemies to shoot at, now can we?

So open up HelloWorldLayer.h and create an array for us to keep track of the enemy tanks in:


NSMutableArray * _enemyTanks;


Then open up HelloWorldLayer.m and add this code to the bottom of init to create a bunch of tanks:


_enemyTanks = [NSMutableArray array];
int NUM_ENEMY_TANKS = 50;
for (int i = 0; i < NUM_ENEMY_TANKS; ++i) {

Tank * enemy = [[Tank alloc] initWithLayer:self type:2 hp:2];
CGPoint randSpot;
BOOL inWall = YES;

while (inWall) {           
randSpot.x = CCRANDOM_0_1() * [self tileMapWidth];
randSpot.y = CCRANDOM_0_1() * [self tileMapHeight];
inWall = [self isWallAtPosition:randSpot];               
}

enemy.position = randSpot;
[_batchNode addChild:enemy];
[_enemyTanks addObject:enemy];

}


This code should be pretty self explanitory. We create a bunch of tanks at random spots (as long as they aren’t in walls).

Build and run, and you should see tanks all around the map! Since we were careful to allow our tank class to choose the artwork based on the type, they’re differently colored too!

Enemy Tanks on the map

Shooting Enemies


Of course, they’re just sitting around not doing anything, which is no fun! Let’s add some basic logic to these tanks by subclassing the Tank class and overriding some of the methods. We’ll call the class RandomTank, because our tank is going to move around more or less randomly.

So create a new file with the iOS\Cocoa Touch\Objective-C class template. Name the class RandomTank and make it a subclass of Tank. Open up RandomTank.h and replace it with the following:


#import "Tank.h"

@interface RandomTank : Tank {
double _timeForNextShot;
}

@end


This adds a instance variable we keep track of how many seconds till we shoot next.

Move to RandomTank.m and replace it with the following:


#import "RandomTank.h"
#import "HelloWorldLayer.h"

@implementation RandomTank

- (id)initWithLayer:(HelloWorldLayer *)layer type:(int)type hp:(int)hp {

if ((self = [super initWithLayer:layer type:type hp:hp])) {
[self schedule:@selector(move:) interval:0.5];
}
return self;

}

- (BOOL)shouldShoot {

if (ccpDistance(self.position, _layer.tank.position) > 600) return NO;

if (_timeSinceLastShot > _timeForNextShot) {       
_timeSinceLastShot = 0;
_timeForNextShot = (CCRANDOM_0_1() * 3) + 1;
[self shootToward:_layer.tank.position];
return YES;
} else {
return NO;
}
}

- (void)calcNextMove {

// TODO  

}

- (void)move:(ccTime)dt {

if (self.moving && arc4random() % 3 != 0) return;   
[self calcNextMove];

}

@end


Here we schedule a move method to be called every half a second. Jumping down to the implementation, every time it calls it has a 1 in 3 chane to move the tank to another direction. We’re gonna skip over implementing that right now and focus on the shooting though.

As far as the shooting goes, we first check to make sure the enemy tank is close enough to the hero tank. We don’t want enemies far away shooting at our tank in this game, or it would be too hard.

We then figure out a random time for the next shot – somewhere between 1-4 seconds. If it’s reached that time, we update the target to wherever the tank is and go ahead and shoot.

Let’s try this out! Make the following chages in HelloWorldLayer.m:


// Add to top of file
#import "RandomTank.h"

// Modify the line in init to create a RandomTank instead of a normal tank
RandomTank * enemy = [[RandomTank alloc] initWithLayer:self type:2 hp:2];


That’s it! Compile and run, and now the tanks will shoot at you when you draw near!

Shooting enemies

Moving Enemies


So far our enemies are shooting, but we haven’t finished making them move.

To keep things simple for this game, the strategy we want to take is:

  1. Pick a nearby random spot.
  2. Make sure there’s a clear path to that spot. If so, move toward it!
  3. Otherwise, return to step 1.

The only tricky thing is “making sure there’s a clear path to that spot.” Given a start and end tile coordinate, how can we walk through all of the tiles that the tank would move between and make sure they’re all clear?

Luckily, this is a solved problem, and James McNeill has an excellent blog post on the matter. We’ll just take his implementation and plug it in.

So go back to RandomTank.m and replace the calcNextMove method with the following:


// From http://playtechs.blogspot.com/2007/03/raytracing-on-grid.html
- (BOOL)clearPathFromTileCoord:(CGPoint)start toTileCoord:(CGPoint)end
{
int dx = abs(end.x - start.x);
int dy = abs(end.y - start.y);
int x = start.x;
int y = start.y;
int n = 1 + dx + dy;
int x_inc = (end.x > start.x) ? 1 : -1;
int y_inc = (end.y > start.y) ? 1 : -1;
int error = dx - dy;
dx *= 2;
dy *= 2;

for (; n > 0; --n)
{
if ([_layer isWallAtTileCoord:ccp(x, y)]) return FALSE;

if (error > 0)
{
x += x_inc;
error -= dy;
}
else
{
y += y_inc;
error += dx;
}
}

return TRUE;
}

- (void)calcNextMove {

BOOL moveOK = NO;
CGPoint start = [_layer tileCoordForPosition:self.position];
CGPoint end;

while (!moveOK) {

end = start;
end.x += CCRANDOM_MINUS1_1() * ((arc4random() % 10) + 3);
end.y += CCRANDOM_MINUS1_1() * ((arc4random() % 10) + 3);

moveOK = [self clearPathFromTileCoord:start toTileCoord:end];   
}   

CGPoint moveToward = [_layer positionForTileCoord:end];

self.moving = YES;
[self moveToward:moveToward];   

}


Don’t worry about how the first method works (although you can read the blog post if you’re curious) – just know it checks to see if there is a wall at any coordinate inbetween the start and end tile coordinates, and returns FALSE if so.

In calcNextMove, we follow our algorithm as described above. Pretty straigtforward eh?

That’s it – build and run, and now you have moving enemies!

Collisions, Explosions, and Exits


Now that we have enemies to shoot at and bullets to dodge, I know what you guys want… tons of explosions, and a way to win the game!

Glad to oblige. Make the following changes to HelloWorldLayer.h:


// Add before @interface
typedef enum {
kEndReasonWin,
kEndReasonLose
} EndReason;

// Add inside @interface
CCParticleSystemQuad * _explosion;
CCParticleSystemQuad * _explosion2;
BOOL _gameOver;
CCSprite * _exit;


Next switch to HelloWorldLayer.m and add this to the bottom of init:


_explosion = [CCParticleSystemQuad particleWithFile:@"explosion.plist"];
[_explosion stopSystem];
[_tileMap addChild:_explosion z:1];

_explosion2 = [CCParticleSystemQuad particleWithFile:@"explosion2.plist"];
[_explosion2 stopSystem];
[_tileMap addChild:_explosion2 z:1];

_exit = [CCSprite spriteWithSpriteFrameName:@"exit.png"];
CGPoint exitTileCoord = ccp(98, 98);
CGPoint exitTilePos = [self positionForTileCoord:exitTileCoord];
_exit.position = exitTilePos;
[_batchNode addChild:_exit];

self.scale = 0.5;


Here we create the two types of explosions we’ll be using and add them to the tile map, but make sure they’re turned off. When we want to use them, we’ll move them to where they should run and start them with resetSystem.

We also add an exit to the bottom right corner of the map. Once the tank reaches this spot, you win!

Finally note we set the scale of the layer to 0.5 because this game works a lot better when you can see more of the map at a time.

Next add these new methods right before update:


- (void)restartTapped:(id)sender {
[[CCDirector sharedDirector] replaceScene:[CCTransitionZoomFlipX transitionWithDuration:0.5 scene:[HelloWorldLayer scene]]];  
}

- (void)endScene:(EndReason)endReason {

if (_gameOver) return;
_gameOver = true;

CGSize winSize = [CCDirector sharedDirector].winSize;

NSString *message;
if (endReason == kEndReasonWin) {
message = @"You win!";
} else if (endReason == kEndReasonLose) {
message = @"You lose!";
}

CCLabelBMFont *label;
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
label = [CCLabelBMFont labelWithString:message fntFile:@"TanksFont.fnt"];
} else {
label = [CCLabelBMFont labelWithString:message fntFile:@"TanksFont.fnt"];
}
label.scale = 0.1;
label.position = ccp(winSize.width/2, winSize.height * 0.7);
[self addChild:label];

CCLabelBMFont *restartLabel;
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
restartLabel = [CCLabelBMFont labelWithString:@"Restart" fntFile:@"TanksFont.fnt"];   
} else {
restartLabel = [CCLabelBMFont labelWithString:@"Restart" fntFile:@"TanksFont.fnt"];   
}

CCMenuItemLabel *restartItem = [CCMenuItemLabel itemWithLabel:restartLabel target:self selector:@selector(restartTapped:)];
restartItem.scale = 0.1;
restartItem.position = ccp(winSize.width/2, winSize.height * 0.3);

CCMenu *menu = [CCMenu menuWithItems:restartItem, nil];
menu.position = CGPointZero;
[self addChild:menu];

[restartItem runAction:[CCScaleTo actionWithDuration:0.5 scale:4.0]];
[label runAction:[CCScaleTo actionWithDuration:0.5 scale:4.0]];

}


These are my handy “game over” methods that I use very often when prototyping games. The most dedicated tutorial readers among you may remember this method from several other tutorials ;] Anyway we will use this to restart the game, and I won’t cover it in detail here since it’s pretty simple stuff.

Then add this code to the beginning of update:


// 1
if (_gameOver) return;

// 2
if (CGRectIntersectsRect(_exit.boundingBox, _tank.boundingBox)) {
[self endScene:kEndReasonWin];
}

// 3
NSMutableArray * childrenToRemove = [NSMutableArray array];
// 4
for (CCSprite * sprite in self.batchNode.children) {
// 5
if (sprite.tag != 0) { // bullet     
// 6       
if ([self isWallAtPosition:sprite.position]) {
[childrenToRemove addObject:sprite];
continue;
}
// 7
if (sprite.tag == 1) { // hero bullet
for (int j = _enemyTanks.count - 1; j >= 0; j--) {
Tank *enemy = [_enemyTanks objectAtIndex:j];
if (CGRectIntersectsRect(sprite.boundingBox, enemy.boundingBox)) {

[childrenToRemove addObject:sprite];
enemy.hp--;
if (enemy.hp <= 0) {
[[SimpleAudioEngine sharedEngine] playEffect:@"explode3.wav"];
_explosion.position = enemy.position;
[_explosion resetSystem];
[_enemyTanks removeObject:enemy];
[childrenToRemove addObject:enemy];
} else {
[[SimpleAudioEngine sharedEngine] playEffect:@"explode2.wav"];
}
}
}
}
// 8
if (sprite.tag == 2) { // enemy bullet                
if (CGRectIntersectsRect(sprite.boundingBox, self.tank.boundingBox)) {                   
[childrenToRemove addObject:sprite];
self.tank.hp--;

if (self.tank.hp <= 0) {
[[SimpleAudioEngine sharedEngine] playEffect:@"explode2.wav"];                       
_explosion.position = self.tank.position;
[_explosion resetSystem];
[self endScene:kEndReasonLose];
} else {
_explosion2.position = self.tank.position;
[_explosion2 resetSystem];
[[SimpleAudioEngine sharedEngine] playEffect:@"explode1.wav"];                       
}
}
}
}
}
for (CCSprite * child in childrenToRemove) {
[child removeFromParentAndCleanup:YES];
}


This is our collision detection and game logic. Let’s walk through it bit by bit.

  1. We’re starting to keep track of whether the game is over, and there’s no need to do any of this if the game is over. This is set when we call the endScene method we just added.
  2. If the tank intersects the exit, the player wins!
  3. We’re about to start checking for collisions, and sometimes when things collide a sprite might be removed from the scene (for example, if a bullet intersects with a tank or a wall the bullet will be removed). However since we’re iterating through the list of the children, we can’t modify the list as we’re iterating it. So we simply add what we want to remove to an array, and remove when we’re all done.
  4. We set a tag on bullet sprites so we could identify them easy – equal to the type of the tank that fired it (1 or 2). We don’t have a tag on anything else, so if there’s a tag we know it’s a bullet.
  5. If there’s a wall where the bullet is, remove the bullet.
  6. If it’s a bullet the hero shot, check to see if it hit any enamy tanks. If it does, reduce the enemy’s HP (and destroy it if it’s dead). Also play some gratuitous explosion sound effects and possibly an explosion particle system!
  7. Similarly, if it’s an enemy bullet check to see if it’s hit the player and react appropriately. Game over if the player reaches 0 HP.

As the last step, put this at the beginning of accelerometer:didAccelerate, ccTouchesBegan, and ccTouchesMoved:


if (_gameOver) return;


Build and run, and see if you can beat the game – and no fair hacking the code to win! ;]

You win!

The Final Challenge


As a final challenge to this project, why not try adding a HUD layer to this project yourself? Here’s the specifications:

  • There should be a line that shows your current number of lives.
  • There should be a line that says “Exit:” with an arrow next to it. The arrow should point in the direction of the exit, relative ot the tank.

This should be a good review of working with multiple layers, passing data between layers, and working with some vector math functions. If you get stuck, you might want to review the How to Create a HUD Layer with Cocos2D tutorial… or you could always cheat by looking at the solution at the end of the article ;]

Happy hacking!

Where To Go From Here?


Here is an example project with all of the code from the above tutorial series (including the optional HUD challenge).

At this point, you have the basics of a pretty fun game! Feel free to add additional features, change out the artwork, and use it as a basis for an app of your own!

If you have any questions or comments on this tutorial, please join the forum discussion below!

How To Make A Multi-directional Scrolling Shooter Part 2 is a post from: Ray Wenderlich

2011年12月8日星期四

How To Make A Multi-Directional Scrolling Shooter Part 1

How To Make A Multi-Directional Scrolling Shooter Part 1:

A while back in the weekly tutorial vote, you guys said you wanted a tutorial on how to make a multi-directional scrolling shooter. Your wish is my command! :]


In this tutorial series, we’ll make a tile-based game where you drive a tank around using the accelerometer. Your goal is to get to the exit, without being blasted by enemy tanks!


To see what we’ll make, check out this video:



In this first part of the series, you’ll get some hands on experience with Cocos2D 2.X, porting it to use ARC, using Cocos2D vector math functions, working with tile maps, and much more!


This tutorial assumes you have some basic knowledge of Cocos2D. If you are new to Cocos2D, you may wish to check out some of the other Cocos2D tutorials on this site first. In particular, you should review the tile-based game tutorial before this tutorial.


Rev up your coding engines, and let’s begin!



Getting Started


We’re going to use Cocos2D 2.X in this project, so go ahead and download it if you don’t have it already.


Double click the tar to unarchive it, then install the templates with the following commands:


cd ~/Downloads/cocos2d-iphone-2.0-beta
./install-templates.sh -f -u

Next create a new project in Xcode with the iOS/cocos2d/cocos2d template, and name it Tanks.


We want to use ARC in this project to make memory management simpler, but by default the template isn’t set up to use ARC. So let’s fix that by performing the following 5 steps:


  1. Control-click the libs folder in your Xcode project and click Delete. Then click Delete again to delete the files permanently. This removes the Cocos2D files from our project – but that’s OK, because we will link in the project separately in a minute. We are doing this so we can set up our project to use ARC (but allow the Cocos2D code to be non-ARC).
  2. Find where you downloaded Cocos2D 2.0 to, and find the cocos2d-ios.xcodeproj inside. Drag that into your project.
  3. Click on your project, select the Tanks target, and go to the Build Phases tab. Expand hte Link Binary With Libraries section, click the + button, select libcocos2d.a and libCocosDenhion.a from the list, and click add.

Linking Cocos2D libs


  1. Click the Build Settings tab and scroll down to the Search Paths section. Set Always Search User Paths to YES, double click User Header Search Paths, and enter in the path to the directory where you’re storing Cocos2D 2.0. Make sure Recursive is checked.

Adding Cocos2D User Header Paths


  1. From the main menu go to Edit\Refactor\Convert to Objective-C ARC. Select all of the files from the dropdown and go through the wizard. It should find no problems, so just finish up the conversion.

And that’s it! Build and run and make sure everything still works OK – you should see the normal Hello World screen.


But you might notice that it’s in portrait mode. We want landscape mode for our game, so open RootViewController.m and make sure shouldAutorotateToInterfaceOrientation looks like the following:



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


Build and run and now we have a landscape game with the latest and greatest version of Cocos2D 2.0, ARC compatibile. w00t!


Adding the Resources


First things first – download the resources for this project and drag the two folders inside (Art and Sounds) into your project. Make sure “Copy items into destination group’s folder” is checked, and “Create groups for any added folders” is selected, and click Finish.


Here’s what’s inside:


  • Two particle effects I made with Particle Designer – two different types of explosions.
  • Two sprite sheets I made with Texture Packer. One contains the background tiles, and one contains the foreground sprites.
  • A font I made with Glyph Designer that we’ll use in the HUD and game over menu.
  • Some background music I made with Garage Band.
  • Some sound effects I made with cxfr.
  • The tile map itself, which I made with Tiled.

The most important thing here is obviously the tile map. I recommend you download Tiled if you don’t have it already, and use it to open up tanks.tmx to take a look.


A tile map made with Tiled


As you can see, it’s a pretty simple map with just three types of tiles – water, grass, and wood (for bridges). If you right click on the water tile and click Properties, you’ll see that it has a property for “Wall” defined, which we’ll be referring to in code later:


A tile map property defined with Tiled


There’s just one layer (named “Background”), and we don’t add anything onto the map for the sprites like the tanks or the exit – we’ll add those in code.


Feel free to modify this map to your desire! For more info on using Tiled, see our earlier tile-based game tutorial.

Adding the Tile Map and Helpers


Next let’s add the tile map to our scene. As you know, this is ridiculously easy in Cocos2D.


Open HelloWorldLayer.h and add two instance variables into HelloWorldLayer:



CCTMXTiledMap * _tileMap;
CCTMXLayer * _bgLayer;


We’re keeping track of the tile map and the one and only layer inside (the background layer) in these variables, because we’ll need to refer to them often.


Then open HelloWorldLayer.m and replace the init method with the following:



-(id) init
{
if( (self=[super init])) {

_tileMap = [CCTMXTiledMap tiledMapWithTMXFile:@"tanks.tmx"];
[self addChild:_tileMap];

_bgLayer = [_tileMap layerNamed:@"Background"];

}
return self;
}


Here we just create the tile map, add it to the layer, and get a reference to the background layer in the tile map.


Build and run, and you’ll see the bottom left corner of the map:


Bottom left corner of the map


In this game we want to start our tank in the upper left corner. To make this easy, let’s build up a series of helper methods. I use these helper methods in almost any tile-based game app I work on, so you might find these handy to use in your own projects as well.


First, we need some methods to get the height and width of the tile map in points. Add these in HelloWorldLayer.m, above init:



- (float)tileMapHeight {
return _tileMap.mapSize.height * _tileMap.tileSize.height;
}

- (float)tileMapWidth {
return _tileMap.mapSize.width * _tileMap.tileSize.width;
}


The mapSize property on a tile map returns the size in number of tiles (not points) so we have to multiply the result by the tileSize to get the size in points.


Next, we need some methods to check if a given position is within the tile map – and likewise for tile coordinate.


In case you forgot what a tile coordinate is, each tile in the map has a coordinate, starting with (0,0) for the upper left and (99,99) for the bottom right (in our case). Here’s a screenshot from the earlier tile-based game tutorial:

Tile Coordinates in Tiled


So add these methods that will verify positions/tile coordinates right after the tileMapWidth method:



- (BOOL)isValidPosition:(CGPoint)position {
if (position.x < 0 ||
position.y < 0 ||
position.x > [self tileMapWidth] ||
position.y > [self tileMapHeight]) {
return FALSE;
} else {
return TRUE;
}
}

- (BOOL)isValidTileCoord:(CGPoint)tileCoord {
if (tileCoord.x < 0 ||
tileCoord.y < 0 ||
tileCoord.x >= _tileMap.mapSize.width ||
tileCoord.y >= _tileMap.mapSize.height) {
return FALSE;
} else {
return TRUE;
}
}


These should be pretty self-explanitory. Obviously negative positions/coordinates would be outside of the map, and the upper bound is the width/height of the map, in points or tiles respectively.


Next, add methods to convert between positions and tile coordinates:



- (CGPoint)tileCoordForPosition:(CGPoint)position {   

if (![self isValidPosition:position]) return ccp(-1,-1);

int x = position.x / _tileMap.tileSize.width;
int y = ([self tileMapHeight] - position.y) / _tileMap.tileSize.height;

return ccp(x, y);
}

- (CGPoint)positionForTileCoord:(CGPoint)tileCoord {

int x = (tileCoord.x * _tileMap.tileSize.width) + _tileMap.tileSize.width/2;
int y = [self tileMapHeight] - (tileCoord.y * _tileMap.tileSize.height) - _tileMap.tileSize.height/2;
return ccp(x, y);

}


The first method converts from a position to a tile coordinate. Converting the x coordinate is easy – it just divides the number of points by the points per tile (discarding the fraction) to get the tile number it’s inside. The y coordinate is similar, except it first has to subtract the y value from the tile map height to “flip” the y value, because positions have 0 at the bottom, but tile coordinates have 0 at the top.


The second method does the oppostie – tile coordinate to position. This is pretty much the same idea, but notice that there are a lot of potential points inside a tile that this method could return. We choose to return the center of the tile here, because that works nicely with Cocos2D since you often want to place a sprite at the center of a tile.


Now that we have this handy library built up, we can now build a routine to allow scrolling the map to center something (namely our tank) within the view. Add this next:



-(void)setViewpointCenter:(CGPoint) position {

CGSize winSize = [[CCDirector sharedDirector] winSize];

int x = MAX(position.x, winSize.width / 2 / self.scale);
int y = MAX(position.y, winSize.height / 2 / self.scale);
x = MIN(x, [self tileMapWidth] - winSize.width / 2 / self.scale);
y = MIN(y, [self tileMapHeight] - winSize.height/ 2 / self.scale);
CGPoint actualPosition = ccp(x, y);

CGPoint centerOfView = ccp(winSize.width/2, winSize.height/2);
CGPoint viewPoint = ccpSub(centerOfView, actualPosition);

_tileMap.position = viewPoint;

}


The easiest way to explain this is through a picture:


Tile Map Scrolling


To make a given point centered, we move the tile map itself. If we subtract our “goal” position from the center of the view, we’ll get the “error” and we can move the map that amount.


The only tricky part is there are certain points we shouldn’t be able to set in the center. If we try to center the map on a position less than half the window size, then empty “black” space would be visible to the user, which isn’t very nice. Same thing for if we try to center a position on the very top of the map. So these checks take care of that.


Now that we have the helper methods in place, let’s try it out! Add the following inside the init method:



CGPoint spawnTileCoord = ccp(4,4);
CGPoint spawnPos = [self positionForTileCoord:spawnTileCoord];
[self setViewpointCenter:spawnPos];


Build and run, and now you’ll see the upper left of the map – where we’re about to spawn our tank!


Upper left of the map


Adding the Tank


Time to add our hero into the mix!


Create a new file with the iOS\Cocoa Touch\Objective-C class template, enter Tank for the class, and make it a subclass of CCSprite. Then open Tank.h and replace it with the following:



#import "cocos2d.h"
@class HelloWorldLayer;

@interface Tank : CCSprite {
int _type;
HelloWorldLayer * _layer;
CGPoint _targetPosition;
}

@property (assign) BOOL moving;
@property (assign) int hp;

- (id)initWithLayer:(HelloWorldLayer *)layer type:(int)type hp:(int)hp;
- (void)moveToward:(CGPoint)targetPosition;

@end


Let’s cover the instance variablers/properties inside this class:


  • type: We have two types of tanks, so this is either 1 or 2. Based on this we can select the proper sprites.
  • layer: We’ll need to call some methods in the layer later on from within the tank class, so we store a reference here.
  • targetPosition: The tank always has a position it’s trying to move toward. We store that here.
  • moving: Keeps track of whether the tank is currently trying to move or not.
  • hp: Keeps track of the tank’s HP, which we’ll be using later.

Next open Tank.m and replace it with the following:



#import "Tank.h"
#import "HelloWorldLayer.h"

@implementation Tank
@synthesize moving = _moving;
@synthesize hp = _hp;

- (id)initWithLayer:(HelloWorldLayer *)layer type:(int)type hp:(int)hp {

NSString *spriteFrameName = [NSString stringWithFormat:@"tank%d_base.png", type];   
if ((self = [super initWithSpriteFrameName:spriteFrameName])) {
_layer = layer;
_type = type;
self.hp = hp;    
[self scheduleUpdateWithPriority:-1];
}
return self;
}

- (void)moveToward:(CGPoint)targetPosition {   
_targetPosition = targetPosition;                   
}

- (void)updateMove:(ccTime)dt {

// 1
if (!self.moving) return;

// 2
CGPoint offset = ccpSub(_targetPosition, self.position);
// 3
float MIN_OFFSET = 10;
if (ccpLength(offset) < MIN_OFFSET) return;

// 4
CGPoint targetVector = ccpNormalize(offset);   
// 5
float POINTS_PER_SECOND = 150;
CGPoint targetPerSecond = ccpMult(targetVector, POINTS_PER_SECOND);
// 6
CGPoint actualTarget = ccpAdd(self.position, ccpMult(targetPerSecond, dt));

// 7
CGPoint oldPosition = self.position;
self.position = actualTarget; 

}

- (void)update:(ccTime)dt {   
[self updateMove:dt];       
}

@end


The initializer is pretty straightforward – it just squirrels away the variables passed in, and schedules an update method to be called. You might not have known that you can schedule an update method on any CCNode – but now you do! :] And note the priority is set to -1, because we want this update to run BEFORE the layer’s update (which is run at the default priority of 0).


moveToward just updates the target position – updateMove is where all the action is, and this is called once per frame. Let’s go over what this method does bit by bit:


  1. If moving is false, just bail. Moving will be false when the app first begins.
  2. Subtract the current position from the target position, to get a vector that points in the direction of where we’re going.
  3. Check the length of that line, and see if it’s less than 10 points. If it is, we’re “close enough” and we just return.
  4. Make the directional vector a unit vector (length of 1) by calling ccpNormalize. This makes it easy to make the line any length we want next.
  5. Multiply the vector by however fast we want the tank to travel in a second (150 here). The result is a vector in points/1 second the tank should travel.
  6. This method is being called several times a second, so we multiply this vector by the delta time (around 1/60 of a second) to figure out how much we should actually travel.
  7. Set the position of the tank to what we figured out. We also keep track of the old position in a local variable, which we’ll use soon.

Now let’s put our new tank class to use! Make the following changes to HelloWorldLayer.h:



// Before the @interface
@class Tank;

// After the @interface
@property (strong) Tank * tank;
@property (strong) CCSpriteBatchNode * batchNode;


And the following changes to HelloWorldLayer.m:



// At the top of the file
#import "Tank.h"

// Right after the @implementation
@synthesize batchNode = _batchNode;
@synthesize tank = _tank;

// Inside init
_batchNode = [CCSpriteBatchNode batchNodeWithFile:@"sprites.png"];
[_tileMap addChild:_batchNode];
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"sprites.plist"];

self.tank = [[Tank alloc] initWithLayer:self type:1 hp:5];
self.tank.position = spawnPos;
[_batchNode addChild:self.tank];

self.isTouchEnabled = YES;
[self scheduleUpdate];

// After init
- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

UITouch * touch = [touches anyObject];
CGPoint mapLocation = [_tileMap convertTouchToNodeSpace:touch];

self.tank.moving = YES;
[self.tank moveToward:mapLocation];

}

- (void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {

UITouch * touch = [touches anyObject];
CGPoint mapLocation = [_tileMap convertTouchToNodeSpace:touch];

self.tank.moving = YES;
[self.tank moveToward:mapLocation];

}

- (void)update:(ccTime)dt {

[self setViewpointCenter:self.tank.position];

}


Nothing too fancy here – we create a batch node for the sprites and add it as a child of the tile map (so that we can scroll the tile map and have the sprites in the batch node scroll along with it).


We then create a tank and add it to the batch node. We set up touch routines to call the moveToward method we wrote earlier, and on each update keep the view centered on the tank.


Build and run, and now you can tap the screen to scroll your tank all around the map, in any direction!


Checking for Walls


So far so good, except there’s one major problem – our tank can roll right across the water! This tank does not have the submersive upgrade yet, so we have to nerf him a bit :]


To do this we need to add a couple more helper methods to HelloWorldLayer.h. Add these methods right above init:



-(BOOL)isProp:(NSString*)prop atTileCoord:(CGPoint)tileCoord forLayer:(CCTMXLayer *)layer {
if (![self isValidTileCoord:tileCoord]) return NO;
int gid = [layer tileGIDAt:tileCoord];
NSDictionary * properties = [_tileMap propertiesForGID:gid];
if (properties == nil) return NO;  
return [properties objectForKey:prop] != nil;
}

-(BOOL)isProp:(NSString*)prop atPosition:(CGPoint)position forLayer:(CCTMXLayer *)layer {
CGPoint tileCoord = [self tileCoordForPosition:position];
return [self isProp:prop atTileCoord:tileCoord forLayer:layer];
}

- (BOOL)isWallAtTileCoord:(CGPoint)tileCoord {
return [self isProp:@"Wall" atTileCoord:tileCoord forLayer:_bgLayer];
}

- (BOOL)isWallAtPosition:(CGPoint)position {
CGPoint tileCoord = [self tileCoordForPosition:position];
if (![self isValidPosition:tileCoord]) return TRUE;
return [self isWallAtTileCoord:tileCoord];
}

- (BOOL)isWallAtRect:(CGRect)rect {
CGPoint lowerLeft = ccp(rect.origin.x, rect.origin.y);
CGPoint upperLeft = ccp(rect.origin.x, rect.origin.y+rect.size.height);
CGPoint lowerRight = ccp(rect.origin.x+rect.size.width, rect.origin.y);
CGPoint upperRight = ccp(rect.origin.x+rect.size.width, rect.origin.y+rect.size.height);

return ([self isWallAtPosition:lowerLeft] || [self isWallAtPosition:upperLeft] ||
[self isWallAtPosition:lowerRight] || [self isWallAtPosition:upperRight]);
}


These are just helper methods we’ll use to check if a given tile coordinate/position/rectangle has the “Wall” property. I’m not going to go over these because they are just review from our earlier tile-based game tutorial.

Open up HelloWorldLayer.h and predeclare all of these methods so we can access them from outside the class if we want:



- (float)tileMapHeight;
- (float)tileMapWidth;
- (BOOL)isValidPosition:(CGPoint)position;
- (BOOL)isValidTileCoord:(CGPoint)tileCoord;
- (CGPoint)tileCoordForPosition:(CGPoint)position;
- (CGPoint)positionForTileCoord:(CGPoint)tileCoord;
- (void)setViewpointCenter:(CGPoint) position;
- (BOOL)isProp:(NSString*)prop atTileCoord:(CGPoint)tileCoord forLayer:(CCTMXLayer *)layer;
- (BOOL)isProp:(NSString*)prop atPosition:(CGPoint)position forLayer:(CCTMXLayer *)layer;
- (BOOL)isWallAtTileCoord:(CGPoint)tileCoord;
- (BOOL)isWallAtPosition:(CGPoint)position;
- (BOOL)isWallAtRect:(CGRect)rect;


Then make the following changes to Tank.m:



// Add right before updateMove
- (void)calcNextMove {

}

// Add at bottom of updateMove
if ([_layer isWallAtRect:[self boundingBox]]) {
self.position = oldPosition;
[self calcNextMove];
}


The new code in updateMove checks to see if we’ve moved into a position that is colliding with a wall. If it does, it moves back to the old position and calls calcNextMove. Right now this method does absolutely nothing, but later on we’ll override this in a subclass.


Build and run, and now you should no longer be able to sail across the sea!


Adding Accelerometer Support


For this game, we don’t actually want to move the tank by tapping, because we want to be able to shoot wherever the user taps.


So to move the tank, we’ll use the accelerometer for input. Add these new methods to HelloWorldLayer.m:



- (void)onEnterTransitionDidFinish {

self.isAccelerometerEnabled = YES;

}

- (void)accelerometer:(UIAccelerometer *)accelerometer
didAccelerate:(UIAcceleration *)acceleration {

#define kFilteringFactor 0.75
static UIAccelerationValue rollingX = 0, rollingY = 0, rollingZ = 0;

rollingX = (acceleration.x * kFilteringFactor) +
(rollingX * (1.0 - kFilteringFactor));   
rollingY = (acceleration.y * kFilteringFactor) +
(rollingY * (1.0 - kFilteringFactor));   
rollingZ = (acceleration.z * kFilteringFactor) +
(rollingZ * (1.0 - kFilteringFactor));

float accelX = rollingX;
float accelY = rollingY;
float accelZ = rollingZ;

CGPoint moveTo = _tank.position;
if (accelX > 0.5) {
moveTo.y -= 300;
} else if (accelX < 0.4) {
moveTo.y += 300;
}
if (accelY < -0.1) {
moveTo.x -= 300;
} else if (accelY > 0.1) {
moveTo.x += 300;
}
_tank.moving = YES;
[_tank moveToward:moveTo];

//NSLog(@"accelX: %f, accelY: %f", accelX, accelY);

}


We set isAccelerometerEnabled in onEnterTransitionDidFinish (I had trouble getting it to work if I put it in init because the scene wasn’t “running” at that point).


The first part of this method comes directly from Apple sample code, to filter the accelerometer values so it’s not so “jiggly”. Don’t worry if you don’t understand this, all you really need to know is that it makes things more smooth. If you’re insatiably curious, this is called a high-pass filter, and you can read about it on Wikipedia’s high pass filter entry.


We check the acceleration in the x and y axis, and set the move target for the tank based on that.


That’s it – build and run (make sure your home button is to your left), and now you should be able to move your tank around the map with the accelerometer!


Gratuituous Music


I can’t leave ya guys hanging without some gratuituous music! :] Just make the following mods to HelloWorldLayer.m:



// Add to top of file
#import "SimpleAudioEngine.h"

// Add to end of init
[[SimpleAudioEngine sharedEngine] playBackgroundMusic:@"bgMusic.caf"];
[[SimpleAudioEngine sharedEngine] preloadEffect:@"explode.wav"];
[[SimpleAudioEngine sharedEngine] preloadEffect:@"tank1Shoot.wav"];
[[SimpleAudioEngine sharedEngine] preloadEffect:@"tank2Shoot.wav"];


Build and run, and enjoy some groovy tunes as you explore! :]


Where To Go From Here?


Here is an example project with all of the code form the tutorial series so far.


Stay tuned for the rest of the series, where we’ll start adding shooting, enemies, and action!


In the meantime, if you have any questions or comments on the tutorial so far, please join the forum discussion below!


How To Make A Multi-Directional Scrolling Shooter Part 1 is a post from: Ray Wenderlich