<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>iPhone Game Tutorials</title>
	<atom:link href="http://www.iphonegametutorials.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.iphonegametutorials.com</link>
	<description>Programming Tutorials for iPhone Game Development - Cocos2d, Unity, and others!</description>
	<lastBuildDate>Fri, 27 Apr 2012 06:34:46 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Want to Help iPhone Game Tutorials?</title>
		<link>http://www.iphonegametutorials.com/2012/04/26/what-to-help-iphone-game-tutorials/</link>
		<comments>http://www.iphonegametutorials.com/2012/04/26/what-to-help-iphone-game-tutorials/#comments</comments>
		<pubDate>Thu, 26 Apr 2012 18:28:08 +0000</pubDate>
		<dc:creator>iPhone Game Tutor</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[business tutorials]]></category>
		<category><![CDATA[game]]></category>
		<category><![CDATA[game programming tutorials]]></category>
		<category><![CDATA[graphic tutorials]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[mobile business]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://www.iphonegametutorials.com/?p=539</guid>
		<description><![CDATA[Looking to get your game or product some exposure? Maybe you just want to prove your amazing objective-c game development skills or you just want to give back to the iPhone developers community? Well, we have an opportunity for you! iPhone Game Tutorials has consistently hit over 15k uniques month after month, but unfortunately, for [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.iphonegametutorials.com/wp-content/uploads/2011/07/needhelpiphone.jpg"><img class="alignleft size-medium wp-image-540" title="iphonegametutorial.com needs your help" src="http://www.iphonegametutorials.com/wp-content/uploads/2011/07/needhelpiphone-249x300.jpg" alt="" width="249" height="300" /></a>Looking to get your game or product some exposure?  Maybe you just want to prove your amazing objective-c game development skills or you just want to give back to the iPhone developers community?  Well, we have an opportunity for you!  <a href="http://www.iphonegametutorials.com">iPhone Game Tutorials</a> has consistently hit over 15k uniques month after month, but unfortunately, for those who have been keeping score we&#8217;re finding it hard to maintain a company and post regular tutorials at the same time <img src='http://www.iphonegametutorials.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' />   This is where you come in&#8230;</p>
<p>You start by contacting us at <a href="mailto:info@iphonegametutorials.com">info (at) iphonegametutorials (dot) com</a>&#8230; Then you can choose to build off an existing tutorial on the site or maybe come up with a new tutorial all your own!  You get full credit for that tutorial and it will be displayed on iphonegametutorials.com for all to see &#8211; We&#8217;ll also include a bio / game mention at the bottom of each post.  As if all that wasn&#8217;t enough, you&#8217;ll also be included on the side bar of &#8220;Contributors&#8221; as well!  I don&#8217;t know what could be better for someone trying to show off their chops in the mobile game space or get a little more spotlight on the game they&#8217;ve made!<br />
<span id="more-539"></span><br />
So what are we looking for:  Game programming tutorials, graphic tutorials and mobile business tutorials.  Any tutorials that fit in the game development, game graphics or indie business space are very much welcome!  No experience writing tutorials? No problem, we can help you in the process since we&#8217;ve been doing it for years at this point.  You can even just supply a working snippet of your game mechanic and we can help with the rest!</p>
<p>Thank you to all those people who have been answering questions in the posts in the meantime, we can&#8217;t express how much that means to us.  We hope to have a new tower defense tutorial out this week!</p>
<p>Thanks for all your continued support!<br />
iPhone Game Tutorial Team</p>

<div class="jwsharethis">
Share this: 
<br />
<a href="mailto:?subject=Want%20to%20Help%20iPhone%20Game%20Tutorials%3F&amp;body=http%3A%2F%2Fwww.iphonegametutorials.com%2F2012%2F04%2F26%2Fwhat-to-help-iphone-game-tutorials%2F">
<img src="http://www.iphonegametutorials.com/wp-content/plugins/jw-share-this/email.png" alt="Share this page via Email" />
</a>
<a target="_blank" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.iphonegametutorials.com%2F2012%2F04%2F26%2Fwhat-to-help-iphone-game-tutorials%2F&amp;title=Want+to+Help+iPhone+Game+Tutorials%3F">
<img src="http://www.iphonegametutorials.com/wp-content/plugins/jw-share-this/su.png" alt="Share this page via Stumble Upon" />
</a>
<a target="_blank" href="http://digg.com/submit?url=http%3A%2F%2Fwww.iphonegametutorials.com%2F2012%2F04%2F26%2Fwhat-to-help-iphone-game-tutorials%2F&amp;title=Want+to+Help+iPhone+Game+Tutorials%3F">
<img src="http://www.iphonegametutorials.com/wp-content/plugins/jw-share-this/digg.png" alt="Share this page via Digg this" />
</a>
<a target="_blank" href="http://www.facebook.com/sharer.php?u=http%3A%2F%2Fwww.iphonegametutorials.com%2F2012%2F04%2F26%2Fwhat-to-help-iphone-game-tutorials%2F&amp;t=Want+to+Help+iPhone+Game+Tutorials%3F">
<img src="http://www.iphonegametutorials.com/wp-content/plugins/jw-share-this/fb.png" alt="Share this page via Facebook" />
</a>
<a target="_blank" href="http://twitter.com/intent/tweet?text=I+like+http%3A%2F%2Fwww.iphonegametutorials.com%2F2012%2F04%2F26%2Fwhat-to-help-iphone-game-tutorials%2F&amp;title=Want+to+Help+iPhone+Game+Tutorials%3F">
<img src="http://www.iphonegametutorials.com/wp-content/plugins/jw-share-this/twitter.png" alt="Share this page via Twitter" />
</a>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.iphonegametutorials.com/2012/04/26/what-to-help-iphone-game-tutorials/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>How to Build a Tower Defense Game for the iPhone – Part 9 – Menus</title>
		<link>http://www.iphonegametutorials.com/2012/03/06/how-to-build-a-tower-defense-game-for-the-iphone-part-9-menus/</link>
		<comments>http://www.iphonegametutorials.com/2012/03/06/how-to-build-a-tower-defense-game-for-the-iphone-part-9-menus/#comments</comments>
		<pubDate>Tue, 06 Mar 2012 03:35:37 +0000</pubDate>
		<dc:creator>Aiden Fry</dc:creator>
				<category><![CDATA[Advanced]]></category>
		<category><![CDATA[Cocos2d]]></category>
		<category><![CDATA[Tower Defense]]></category>
		<category><![CDATA[CCLabel]]></category>
		<category><![CDATA[CCLayer]]></category>
		<category><![CDATA[CCMenuItemImage]]></category>
		<category><![CDATA[CCSprite]]></category>
		<category><![CDATA[CCTouchDispatcher]]></category>
		<category><![CDATA[cocos2d]]></category>
		<category><![CDATA[tower defense]]></category>
		<category><![CDATA[tower defense game]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[XCode]]></category>

		<guid isPermaLink="false">http://www.iphonegametutorials.com/?p=749</guid>
		<description><![CDATA[Welcome back! Firstly I would like to apologies for the skittishness of these tutorials, we will be moving onto upgrades in the next tutorial. Gameplay is great, but all games must have a start and an end &#8211; here is where menus come in. The visual style of the menus that we will be implementing [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.iphonegametutorials.com/wp-content/uploads/2012/03/menu.png"><img src="http://www.iphonegametutorials.com/wp-content/uploads/2012/03/menu-300x153.png" alt="" title="menu" width="300" height="153" class="alignleft size-medium wp-image-757" /></a>Welcome back!   Firstly I would like to apologies for the skittishness of these tutorials, we will be moving onto upgrades in the next tutorial.  Gameplay is great, but all games must have a start and an end &#8211; here is where menus come in. The visual style of the menus that we will be implementing have been designed by me (who is definitely not an artist!) in about 5 minutes. However, once you have read through this tutorial feel free to go back and make the visuals your own! <img src='http://www.iphonegametutorials.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p>In the meantime, source code and download after the break!</p>
<p><span id="more-749"></span></p>
<p>Lets get to the goodies first, here is the source code: <a href="http://www.iphonegametutorials.com/wp-content/uploads/2012/03/TowerDefensePart9.zip">Tower Defense Part 9</a>.</p>
<p>Firstly lets look at the opening menu, go into the source file and find the new images: menuscreen, pause, cancel and buy, and add them to your project resources file, copying them if needed.  Now create a new class and call it MenuLayer and make it a subclass of CCLayer. </p>
<p>Open MenuLayer.h and add the following:</p>
<pre class="brush:c++">
#import "CCLayer.h"
#import "cocos2d.h"
#import "GameHUD.h"
#import "TutorialScene.h"
next open MenuLayer.m and add the following
-(id)init{
     if ((self = [super init])) {
          CGSize winSize = [[CCDirector sharedDirector] winSize];
          CCSprite *background = [CCSprite spriteWithFile:@"MenuScreen.png"];
          background.position = ccp(winSize.width/2, winSize.height/2);
          [self addChild:background];

          CCMenuItemImage *rangeButton = [CCMenuItemImage itemFromNormalImage:@"Buy.png" selectedImage:@"Buy.png" target:self selector:@selector(startGame)];
          CCMenu *menu = [CCMenu menuWithItems:rangeButton, nil];
          menu.position = ccp(winSize.width/2-65, winSize.height/2-15);
          [menu alignItemsVerticallyWithPadding: 20.0f];
          [self addChild:menu];
     }

     return self;
}

-(void) startGame
{
     [GameHUD resetGameHUD];
     [Tutorial resetGame];
     [self.parent removeChild:self cleanup:TRUE];
     [[CCDirector sharedDirector] resume];
}

-(void) dealloc{
     [super dealloc];
}
</pre>
<p>We should all be fairly familiar with the above by now, however if you are not familiar with menu items it could be a smidge confusing. So we add our menu screen background and add our menu item (the buy<br />
image). When the user clicks this image we run the function startGame. The function start game will remove the menu layer (the game layer &#038; GUI is underneath and hidden), we then reset the game using two functions which we will implement next.</p>
<p>Add this to TutorialScene.h</p>
<pre class="brush:c++">
#import "MenuLayer.h"
</pre>
<p>Open TutorialScene.m and add the following functions</p>
<pre class="brush:c++">
+(void) resetGame{
     reset = YES;
}

-(void) resetLayer{
     reset = NO;

     DataModel *m = [DataModel getModel];
     NSMutableArray *towersToDelete = [[NSMutableArray alloc] init];

     for (Tower *tower in m._towers) {
          [towersToDelete addObject:tower];
          [self removeChild:tower cleanup:YES];
     }

     for (Tower *tower in towersToDelete) {
          [self removeChild:tower cleanup:YES];
     }

     [towersToDelete release];

     for (Creep *target in m._targets) {
          [m._targets removeObject:target];
          [self removeChild:target.healthBar cleanup:YES];
          [self removeChild:target cleanup:YES];
     }

     NSMutableArray *projectilesToDelete = [[NSMutableArray alloc] init];
     for (Projectile *projectile in m._projectiles) {
          [projectilesToDelete addObject:projectile];
     }

     for (Projectile *projectile in projectilesToDelete) {
          [self removeChild:projectile cleanup:YES];
     }

     [projectilesToDelete release];
     [m._towers removeAllObjects];
     [m._targets removeAllObjects];
     [m._projectiles removeAllObjects];
     [m._waves removeAllObjects];
     [self addWaves];

     // Call game logic about every second
     [self schedule:@selector(update:)];
     [self schedule:@selector(gameLogic:) interval:0.2];! !
     self.currentLevel = 0;
     self.position = ccp(-258, -122);
     self.isTouchEnabled = YES;
}
</pre>
<p>Then at the very top of our update cycle add the following:</p>
<pre class="brush:c++">
if (reset == YES) {
     [self resetLayer];
}
</pre>
<p>What&#8217;s going on: These functions work together to reset the game layer, all towers, creeps and projectiles are removed. We reschedule our game loops and set the scene back into its initial position.<br />
Similarly open GameHUD.m and add the following:</p>
<pre class="brush:c++">
+(void) resetGameHUD
{
     resetGameHUD = YES;
}

-(void) resetGameHUDLayer
{
     resetGameHUD = NO;
     [healthBar setSprite:[CCSprite
     spriteWithFile:@"health_bar_green.png"]];
     [healthBar setScale:0.5];

     baseHpPercentage = 99;
     [healthBar setPercentage:baseHpPercentage];
     [self updateBaseHp:+1];
     waveCount = 0;
     [waveCountLabel setString:[NSString stringWithFormat: @"Wave 1"]];
     resources = baseAttributes.baseStartingMoney;
     [resourceLabel setString:[NSString stringWithFormat: @"Money $%i",resources]];
}
</pre>
<p>and at the top of update:</p>
<pre class="brush:c++">
if (resetGameHUD == YES) {
     [self resetGameHUDLayer];
}
</pre>
<p>What&#8217;s going on: These functions also work together to reset the gameHUD.  We reset our health bar, wave count and the money available. Simples. Now if you build and run this program, not a lot different will happen.  First we need to add our menu screen so that it loads straight away.</p>
<p>Open TutorialScene.m and go to the top where the +(id)scene method is.  Below where we add our GameHUD add the following:</p>
<pre class="brush:c++">
CCLayer *menuLayer =[[[MenuLayer alloc]init ]autorelease];
[scene addChild:menuLayer z:10];
[[CCDirector sharedDirector] pause];
</pre>
<p>What this does is load our menu layer, put it above our game and HUD layers then we pause the CCDirector so that the game does not play in the background.  Run this and we should see our menu working perfectly.</p>
<p><strong>End Game</strong><br />
There are two ways to reach the end of the game at the moment, either the base health runs out and the player loses, or the player reaches the end of the waves which we have set out (in this case they complete wave 5). As such we shall create an endGame layer which can either be Win or Lose.<br />
Create a new class called EndGame and make it a sub-class of CCLayerColor (this could be a CCLayer, but why not find out about this new class type).</p>
<p>Add the following to EndGame.h :</p>
<pre class="brush:c++">
#import "CCLayer.h"
#import "cocos2d.h"
#import "GameHUD.h"
#import "TutorialScene.h"
#import "MenuLayer.h"
@interface EndGame : CCLayerColor{
}

-(id)init:(bool)win;

@end
</pre>
<p>Then in EndGame.m add the following</p>
<pre class="brush:c++">
-(id) init:(bool) win
{
     if( (self=[super initWithColor:ccc4(150,50,50,255)])) {
          CGSize winSize = [[CCDirector sharedDirector] winSize];
          self.isTouchEnabled = YES;
          GameHUD *gameHUD;
          gameHUD = [GameHUD sharedHUD];

          CCLabelTTF *endGameLabel = [CCLabelTTF labelWithString:@"" dimensions:CGSizeMake(150, 40) alignment:UITextAlignmentRight fontName:@"Marker Felt" fontSize:30];
          endGameLabel.position = ccp((winSize.width/2-10), (winSize.height - 30));
          endGameLabel.color = ccc3(255,80,20);

          [self addChild:endGameLabel z:1];

          if (win == NO){
               [endGameLabel setString:[NSString stringWithFormat: @"Game Over!"]];
          }
          else {
               [endGameLabel setString:[NSString stringWithFormat: @"You Win!"]];
          }

          CCLabelTTF *welldoneLabel = [CCLabelTTF labelWithString:@"" dimensions:CGSizeMake(300, 40) alignment:UITextAlignmentRight fontName:@"Marker Felt" fontSize:30];
          welldoneLabel.position = ccp((winSize.width/2-30), (winSize.height/2 + 75));
          welldoneLabel.color = ccc3(255,80,20);

          [self addChild:welldoneLabel z:1];

          [welldoneLabel setString:[NSString stringWithFormat: @"You reached wave %i",gameHUD.waveCount]];
          CCLabelTTF *restartLabel = [CCLabelTTF labelWithString:@"Restart?" dimensions:CGSizeMake(300, 40) alignment:UITextAlignmentRight fontName:@"Marker Felt" fontSize:30];

          restartLabel.position = ccp((winSize.width/2 - 150), (winSize.height/2));
          restartLabel.color = ccc3(255,80,20);

          [self addChild:restartLabel z:1];

          CCLabelTTF *menuLabel = [CCLabelTTF labelWithString:@"Menu" dimensions:CGSizeMake(300, 40) alignment:UITextAlignmentRight fontName:@"Marker Felt" fontSize:30];
          menuLabel.position = ccp((winSize.width/2 - 150), (winSize.height/2-50));
          menuLabel.color = ccc3(255,80,20);

          [self addChild:menuLabel z:1];

          CCMenuItemImage *replayButton;
          CCMenuItemImage *menuButton;
          CCMenu *menu;

          replayButton = [CCMenuItemImage
          itemFromNormalImage:@"Buy.png" selectedImage:@"Buy.png" target:self selector:@selector(replayLevel)];
          menuButton = [CCMenuItemImage itemFromNormalImage:@"Buy.png" selectedImage:@"Buy.png" target:self selector:@selector(returnToMenu)];
          menu = [CCMenu menuWithItems: replayButton, menuButton, nil];

          menu.position = ccp((winSize.width/2 + 50), (winSize.height/2-22));
          [menu alignItemsVerticallyWithPadding: 5.0f];

          [self addChild:menu];
          [[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:10 swallowsTouches:YES];
     }

     return self;
}

-(void) replayLevel
{
     //Reset the game and start from the beginning.
     [GameHUD resetGameHUD];
     [Tutorial resetGame];
     [self.parent removeChild:self cleanup:TRUE];
     [[CCDirector sharedDirector] resume];
}

-(void) returnToMenu
{
     CCLayer *menuLayer =[[[MenuLayer alloc]init ]autorelease];
     [self.parent addChild:menuLayer z:10];
     [self.parent removeChild:self cleanup:TRUE];
}

-(void) dealloc{
     [super dealloc];
}
</pre>
<p>Very similar to GameHUD: we add all our text via labels, rather than using a background image (like MenuLayer). The advantage is that we can tweak our layout in xcode, rather than opening Photoshop and re-importing, however this can become very fiddly&#8230;</p>
<p>The init function has a bool variable associated with it, this we use to adjust the text on screen to say either “You Win”, or “You Lose”.  We added two clickable menu items on this scene, one to replay the level<br />
and another to return to the menu screen. ReplayLevel function is almost exactly the same as the start game function from MenuLayer.</p>
<p>The returnToMenu function simply creates and adds the menu layer, then removes the endgame layer.</p>
<p><strong>Calling the endGame: Win </strong></p>
<p>Open TutorialScene.m and find our update function, and find the piece of<br />
code that searches for the end of the current wave and adjust it to the following:</p>
<pre class="brush:c++">
Wave *wave = [self getCurrentWave];
if ([m._targets count] ==0 &#038;&#038; wave.redCreeps <= 0 &#038;&#038; wave.greenCreeps <= 0 &#038;&#038; wave.brownCreeps <= 0) {
     if (self.currentLevel == 5) {
          CCLayerColor *endGameLayer =[[[EndGame alloc]init:YES]autorelease];
          [self.parent addChild:endGameLayer z:10];
          [[CCDirector sharedDirector] pause];
     }
     else{
          [self schedule:@selector(waveWait) interval:3.0];
          [gameHUD newWaveApproaching];
     }
}
</pre>
<p>We have added a search for the last wave (wave 5) when this is selected we load the endGameLayer with a “WIN = YES” call and pause the game. </p>
<p><strong>Calling the endGame: Loose</strong></p>
<p>Open GameHUD.m and adjust the updateBaseHp method to the following:</p>
<pre class="brush:c++">
-(void) updateBaseHp:(int)amount{
     baseHpPercentage += amount;
     if (baseHpPercentage <= 25) {
          [self->healthBar setSprite:[CCSprite spriteWithFile:@"health_bar_red.png"]];
          [self->healthBar setScale:0.5];
     }

     if (baseHpPercentage <= 0) {
          //Game Over Scenario
          //printf("Game Over\n");
          CCLayerColor *endGameLayer =[[[EndGame alloc]init:NO ]autorelease];
          [self.parent addChild:endGameLayer z:10];
          [[CCDirector sharedDirector] pause];
     }

     [self->healthBar setPercentage:baseHpPercentage];
}
</pre>
<p>When the baseHp goes <= 0 we load the endGameLayer with a call “WIN = NO” and pause the game.<br />
Run the game at this point and all should be working fine. </p>
<p><strong>Pause</strong></p>
<p>While we are doing menus lets create a pause menu.<br />
Create a new class called PauseLayer and make it a subclass of CCLayerColor.</p>
<p>Add the following to PauseLayer.h :</p>
<pre class="brush:c++">
#import "CCLayer.h"
#import "cocos2d.h"
#import "GameHUD.h"
#import "EndGame.h"
#import "TutorialScene.h"
#import "MenuLayer.h"
@interface PauseLayer : CCLayerColor{
}

@end

Next add the following to PauseLayer.m :

-(id) init
{
     if( (self=[super initWithColor:ccc4(150,50,50,255)])) {
          CGSize winSize = [[CCDirector sharedDirector] winSize];
          self.isTouchEnabled = YES;

          GameHUD *gameHUD;
          gameHUD = [GameHUD sharedHUD];
          CCLabelTTF *endGameLabel = [CCLabelTTF labelWithString:@"" dimensions:CGSizeMake(150, 40) alignment:UITextAlignmentRight fontName:@"Marker Felt" fontSize:30];
          endGameLabel.position = ccp((winSize.width/2-10), (winSize.height - 30));
          endGameLabel.color = ccc3(255,80,20);

          [self addChild:endGameLabel z:1];

          if (gameHUD.waveCount != 5){
               [endGameLabel setString:[NSString stringWithFormat: @"Paused"]];
          }

          CCLabelTTF *welldoneLabel = [CCLabelTTF labelWithString:@"" dimensions:CGSizeMake(300, 40) alignment:UITextAlignmentRight fontName:@"Marker Felt" fontSize:30];
          welldoneLabel.position = ccp((winSize.width/2-30), (winSize.height/2 + 75));
          welldoneLabel.color = ccc3(255,80,20);

          [self addChild:welldoneLabel z:1];

          [welldoneLabel setString:[NSString stringWithFormat: @"You reached wave %i",gameHUD.waveCount]];
          CCLabelTTF *restartLabel = [CCLabelTTF labelWithString:@"Continue" dimensions:CGSizeMake(300, 40) alignment:UITextAlignmentRight fontName:@"Marker Felt" fontSize:30];
          restartLabel.position = ccp((winSize.width/2 - 150), (winSize.height/2));
          restartLabel.color = ccc3(255,80,20);

          [self addChild:restartLabel z:1];

          CCLabelTTF *menuLabel = [CCLabelTTF labelWithString:@"Quit" dimensions:CGSizeMake(300, 40) alignment:UITextAlignmentRight fontName:@"Marker Felt" fontSize:30];
          menuLabel.position = ccp((winSize.width/2 - 150), (winSize.height/2-50));
          menuLabel.color = ccc3(255,80,20);

          [self addChild:menuLabel z:1];

          CCMenuItemImage *replayButton;
          CCMenuItemImage *menuButton;
          CCMenu *menu;
          replayButton = [CCMenuItemImage itemFromNormalImage:@"Buy.png" selectedImage:@"Buy.png" target:self selector:@selector(continueLevel)];
          menuButton = [CCMenuItemImage itemFromNormalImage:@"Cancel.png" selectedImage:@"Cancel.png" target:self selector:@selector(returnToMenu)];
          menu = [CCMenu menuWithItems: replayButton, menuButton, nil];
          menu.position = ccp((winSize.width/2 + 50), (winSize.height/ 2-22));

          [menu alignItemsVerticallyWithPadding: 5.0f];
          [self addChild:menu];
          [[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:10 swallowsTouches:YES];
     }

     return self;
}

-(void) continueLevel
{
     //Replay Game
     [self.parent removeChild:self cleanup:TRUE];
     [[CCDirector sharedDirector] resume];
}

-(void) returnToMenu
{
     //Return to menu
     CCLayer *menuLayer =[[[MenuLayer alloc]init ]autorelease];
     [self.parent addChild:menuLayer z:10];
     [self.parent removeChild:self cleanup:TRUE];
}

-(void)dealloc
{
     [super dealloc];
}
</pre>
<p>Similarly to EndGame we use a CCLayerColor and add our text using labels. We then create two selectable icons, one will return the player to the game, and the other to the start menu, these methods should be clear now as they are basically the same as we have used in other menus.</p>
<p>Now we'll access the pause menu - Open GameHUD.m and add the following to the bottom of the init method. </p>
<pre class="brush:c++">
CCMenuItemImage *pauseButton = [CCMenuItemImage
itemFromNormalImage:@"Pause.png" selectedImage:@"Pause.png" target:self
selector:@selector(pauseGame)];
pauseButton.scale = 0.13;
CCMenu *menu = [CCMenu menuWithItems:pauseButton, nil];
menu.position = ccp(winSize.width -35, 35);
[menu alignItemsVerticallyWithPadding: 20.0f];
[self addChild:menu];
</pre>
<p>Then add the following method:</p>
<pre class="brush:c++">
-(void) pauseGame
{
     CCLayerColor *pauseLayer =[[[PauseLayer alloc]init]autorelease];
     [self.parent addChild:pauseLayer z:10];
     [[CCDirector sharedDirector] pause];
}
</pre>
<p>We simply place our pause image at the bottom right of the screen, and when it is selected we run the pauseLayer and pause the game.  There we go, these are three very simple menus for our game. </p>
<p><em>Homework:</em> Why not try creating a “score”. Combine the number of enemies killed (give each creep class a different value) plus bonuses for completing a round (or anything else that you want to give points for). Then when the end game is shown, tell the player their score. </p>
<p>Good luck! <img src='http://www.iphonegametutorials.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>

<div class="jwsharethis">
Share this: 
<br />
<a href="mailto:?subject=How%20to%20Build%20a%20Tower%20Defense%20Game%20for%20the%20iPhone%20%E2%80%93%20Part%209%20%E2%80%93%20Menus&amp;body=http%3A%2F%2Fwww.iphonegametutorials.com%2F2012%2F03%2F06%2Fhow-to-build-a-tower-defense-game-for-the-iphone-part-9-menus%2F">
<img src="http://www.iphonegametutorials.com/wp-content/plugins/jw-share-this/email.png" alt="Share this page via Email" />
</a>
<a target="_blank" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.iphonegametutorials.com%2F2012%2F03%2F06%2Fhow-to-build-a-tower-defense-game-for-the-iphone-part-9-menus%2F&amp;title=How+to+Build+a+Tower+Defense+Game+for+the+iPhone+%E2%80%93+Part+9+%E2%80%93+Menus">
<img src="http://www.iphonegametutorials.com/wp-content/plugins/jw-share-this/su.png" alt="Share this page via Stumble Upon" />
</a>
<a target="_blank" href="http://digg.com/submit?url=http%3A%2F%2Fwww.iphonegametutorials.com%2F2012%2F03%2F06%2Fhow-to-build-a-tower-defense-game-for-the-iphone-part-9-menus%2F&amp;title=How+to+Build+a+Tower+Defense+Game+for+the+iPhone+%E2%80%93+Part+9+%E2%80%93+Menus">
<img src="http://www.iphonegametutorials.com/wp-content/plugins/jw-share-this/digg.png" alt="Share this page via Digg this" />
</a>
<a target="_blank" href="http://www.facebook.com/sharer.php?u=http%3A%2F%2Fwww.iphonegametutorials.com%2F2012%2F03%2F06%2Fhow-to-build-a-tower-defense-game-for-the-iphone-part-9-menus%2F&amp;t=How+to+Build+a+Tower+Defense+Game+for+the+iPhone+%E2%80%93+Part+9+%E2%80%93+Menus">
<img src="http://www.iphonegametutorials.com/wp-content/plugins/jw-share-this/fb.png" alt="Share this page via Facebook" />
</a>
<a target="_blank" href="http://twitter.com/intent/tweet?text=I+like+http%3A%2F%2Fwww.iphonegametutorials.com%2F2012%2F03%2F06%2Fhow-to-build-a-tower-defense-game-for-the-iphone-part-9-menus%2F&amp;title=How+to+Build+a+Tower+Defense+Game+for+the+iPhone+%E2%80%93+Part+9+%E2%80%93+Menus">
<img src="http://www.iphonegametutorials.com/wp-content/plugins/jw-share-this/twitter.png" alt="Share this page via Twitter" />
</a>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.iphonegametutorials.com/2012/03/06/how-to-build-a-tower-defense-game-for-the-iphone-part-9-menus/feed/</wfw:commentRss>
		<slash:comments>23</slash:comments>
		</item>
		<item>
		<title>How to Build a Tower Defense Game for the iPhone – Part 8B – Tower Powers</title>
		<link>http://www.iphonegametutorials.com/2012/02/16/how-to-build-a-tower-defense-game-for-the-iphone-part-8b-tower-powers-2/</link>
		<comments>http://www.iphonegametutorials.com/2012/02/16/how-to-build-a-tower-defense-game-for-the-iphone-part-8b-tower-powers-2/#comments</comments>
		<pubDate>Thu, 16 Feb 2012 06:27:06 +0000</pubDate>
		<dc:creator>Aiden Fry</dc:creator>
				<category><![CDATA[Advanced]]></category>
		<category><![CDATA[Cocos2d]]></category>
		<category><![CDATA[Tower Defense]]></category>
		<category><![CDATA[baseTowerCostPercentage]]></category>
		<category><![CDATA[CannonTower]]></category>
		<category><![CDATA[source code]]></category>
		<category><![CDATA[splash damage]]></category>
		<category><![CDATA[tower defense]]></category>
		<category><![CDATA[tower defense game]]></category>
		<category><![CDATA[Towers]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://www.iphonegametutorials.com/?p=737</guid>
		<description><![CDATA[Hi Again! So in this tutorial we will be implementing towers with splash damage, per-tower upgrades, and creep army upgrades, but before we begin that it&#8217;s time to get us ready for these upgrades. Open the source code and find the files baseAttributes.h and .m. add these files to your project class folder, open them [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.iphonegametutorials.com/wp-content/uploads/2012/02/tut8.png"><img src="http://www.iphonegametutorials.com/wp-content/uploads/2012/02/tut8-300x154.png" alt="" title="tut8" width="300" height="154" class="alignleft size-medium wp-image-731" /></a>Hi Again!  So in this tutorial we will be implementing towers with splash damage, per-tower upgrades, and creep army upgrades, but before we begin that it&#8217;s time to get us ready for these upgrades.</p>
<p>Open the source code and find the files baseAttributes.h and .m. add these files to your project class folder, open them and take a look inside.</p>
<p>Ok, so there are a few variables in here which may be new or unexpected, however if they are not immediately obvious we will be using all these variables in the near future. The main categories of variables are, base health and money variables, Machine Gun variables, Freeze tower variables, Cannon tower variables and Creep variables.</p>
<p>As always &#8211; Source code AND download after the break<br />
<span id="more-737"></span></p>
<p>First things first, if you want to just see everything in action, here is the source code: <a href="http://www.iphonegametutorials.com/wp-content/uploads/2012/02/TowerDefensePart8.zip">Tower Defense Part 8</a>.</p>
<p>GameHUD:</p>
<p>Open gameHUD.h and add the following:</p>
<pre class="brush:c++">
#import “baseAttributes.h”
BaseAttributes *baseAttributes;
</pre>
<p>in gameHUD.M at the top of the init method add:</p>
<pre class="brush:c++">
baseAttributes = [BaseAttributes sharedAttributes];
</pre>
<p>Ok, so we now have access to all the variables kept in baseAttributes. </p>
<p>Add the following lines to replace &#8220;baseHpPercentage = 100;&#8221;</p>
<pre class="brush:c++">
baseHp = baseAttributes.baseHealth;
baseHpPercentage = (baseHp/baseAttributes.baseHealth) *100;
</pre>
<p>Remove resources = 100; and add the following AFTER &#8220;[self addChild:resourceLabel z:1];&#8221;</p>
<pre class="brush:c++">
resources = baseAttributes.baseStartingMoney;
[self->resourceLabel setString:[NSString stringWithFormat: @"Money $%i",resources]];
</pre>
<p>Add the following call at the end of init</p>
<pre class="brush:c++">
[self schedule:@selector(updateResourcesNom) interval: baseAttributes.baseMoneyRegenRate];
</pre>
<p>Change updateResourcesNom function too</p>
<pre class="brush:c++">
-(void) updateResourcesNom{
     [self updateResources:baseAttributes.baseMoneyRegen];
}</pre>
<p>Note: Remove the call to updateResourcesNom from TutorialScene.m -&gt; init function, it just sits better within GameHUD.m Next, we shall take a look at Tower costs in GameHUD.m (init).  First, we are only going to use 3 towers in this game, so remove the 4th tower from the NSArray *images, and change the 3rd tower to “CannonTurret.png” and include the CannonTurret.png image (from the source file) into your Resources folder. We are going to implement the CannonTurret here later, however for now it is useful to have the image here.</p>
<p>Replace the setCost switch statement with the following:</p>
<pre class="brush:c++">
//Set cost values
switch (i) {
     case 0:
          [towerCost setString:[NSString stringWithFormat:@"$ %i", (int) (baseAttributes.baseMGCost*baseAttributes.baseTowerCostPercentage)]];
     break;

     case 1:
          [towerCost setString:[NSString stringWithFormat:@"$ %i",(int) (baseAttributes.baseFCost*baseAttributes.baseTowerCostPercentage)]];
     break;

     case 2:
          [towerCost setString:[NSString stringWithFormat:@"$ %i",(int) (baseAttributes.baseCCost*baseAttributes.baseTowerCostPercentage)]];
     break;

     default:
     break;
}
</pre>
<p>and in TutorialScene.m in addTower method replace the switch statement with the following:</p>
<pre class="brush:c++">
switch (towerTag) {
     case 1:
          if (gameHUD.resources >= (int) (baseAttributes.baseMGCost*baseAttributes.baseTowerCostPercentage)) {
               target = [MachineGunTower tower];
               [gameHUD updateResources:-(int) (baseAttributes.baseMGCost*baseAttributes.baseTowerCostPercentage)];
          }
          else
               return;
          break;

     case 2:
          if (gameHUD.resources >= (int) (baseAttributes.baseFCost*baseAttributes.baseTowerCostPercentage)) {
               target = [FreezeTower tower];
               [gameHUD updateResources:-(int) (baseAttributes.baseFCost*baseAttributes.baseTowerCostPercentage)];
          }
          else
               return;
          break;

     case 3:
          if (gameHUD.resources >= (int) (baseAttributes.baseCCost*baseAttributes.baseTowerCostPercentage)) {
               target = [MachineGunTower tower];//We will change this when we create the CannonTower class.
               [gameHUD updateResources:-(int) (baseAttributes.baseCCost*baseAttributes.baseTowerCostPercentage)];
          }
          else
               return;
          break;

     default:
     break;
}
</pre>
<p>Then we&#8217;re going to want to add this to init method:</p>
<pre class="brush:c++">
baseAttributes = [BaseAttributes sharedAttributes];
</pre>
<p>Moving on to TutorialScene.h:</p>
<pre class="brush:c++">
#import “baseAttributes.h”

BaseAttributes * baseAttributes;
</pre>
<p>Run this and every thing should still be in working order.</p>
<p>More gameHUD:<br />
Add the following method to gameHud.m</p>
<pre class="brush:c++">
-(void) update:(ccTime) dt {
     for (CCSprite *sprite in movableSprites){

          switch (sprite.tag) {
               case 1:
                    if (baseAttributes.baseMGCost*baseAttributes.baseTowerCostPercentage > resources)
                    {
                         sprite.opacity = 50;
                         break;
                    }
                    else
                         sprite.opacity = 255;
                    break;

               case 2:
                    if (baseAttributes.baseFCost*baseAttributes.baseTowerCostPercentage > resources)
                    {
                         sprite.opacity = 50;
                         break;
                    }
                    else
                         sprite.opacity = 255;
                    break;

               case 3:
                    if (baseAttributes.baseCCost*baseAttributes.baseTowerCostPercentage > resources)
                    {
                         sprite.opacity = 50;
                         break;
                    }
                    else
                         sprite.opacity = 255;
                    break;

                    default:
                    break;
         }
     }
}
</pre>
<p>and add a call to update in the init method:</p>
<pre class="brush:c++">
[self schedule:@selector(update:)];
</pre>
<p>Next, replace ccTouchBegan with the following:</p>
<pre class="brush:c++">
- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
     CGPoint touchLocation = [self convertTouchToNodeSpace:touch];

     CCSprite * newSprite = nil;

     for (CCSprite *sprite in movableSprites) {
          if (CGRectContainsPoint(sprite.boundingBox, touchLocation)) {
               if (sprite.opacity == 255) {
                    DataModel *m = [DataModel getModel];
                    m._gestureRecognizer.enabled = NO;
                    selSpriteRange = [CCSprite spriteWithFile:@"Range.png"];

                    switch (sprite.tag) {
                    case 1:
                         selSpriteRange.scale = (baseAttributes.baseMGRange/50);
                    break;

                    case 2:
                         selSpriteRange.scale = (baseAttributes.baseFRange/50);
                    break;

                    case 3:
                         selSpriteRange.scale = (baseAttributes.baseCRange/50);
                    break;

                    default:
                    break;
                    }

                    [self addChild:selSpriteRange z:-1];
                    selSpriteRange.position = sprite.position;

                    newSprite = [CCSprite spriteWithTexture:[sprite texture]]; //sprite;

                    newSprite.position = sprite.position;
                    selSprite = newSprite;
                    selSprite.tag = sprite.tag;

                    [self addChild:newSprite];
               }
               break;
          }
     }
     return YES;
}
</pre>
<p>What do these changes do? Well, we can set now our tower Cost from baseAttributes.m rather than having to change both tutorialscene.m and gamehud.m.  We have also included a scaling factor (baseTowerCostPercentage), which is currently set to 1 (i.e. no change), which we can use later to make all the towers proportionally cheaper/more expensive.</p>
<p>Next we show the image with full opacity only if the player has enough money to buy it. Then in ccTouchesBegan we did two things, one only allow the player to select a tower if the opacity is full (ie we have enough money), then we scale the towerRange image for each tower class individually. (The original file has a diameter of 100, and a range of 50).</p>
<p>Now that we&#8217;ve gotten some nitty gritty class work out of the way we start to make the changes to the class that will really make this a fun time.  So lets get started with Creeps first!</p>
<p>In Creep.m remove the following variables:</p>
<pre class="brush:c++">
float setRedHp = 9;
float setRedSpeed = 6;
float setGreenHp = 18;
float setGreenSpeed = 12;
</pre>
<p>Then in fastRedCreep replace them with:</p>
<pre class="brush:c++">
BaseAttributes* baseAttributes = [BaseAttributes sharedAttributes];
creep.hp = creep.totalHp = baseAttributes.baseRedCreepHealth;
creep.moveDuration = baseAttributes.baseRedCreepMoveDur;
</pre>
<p>In StrongGreenCreep replace them with:</p>
<pre class="brush:c++">
BaseAttributes* baseAttributes = [BaseAttributes sharedAttributes];
creep.hp = creep.totalHp = baseAttributes.baseGreenCreepHealth;
creep.moveDuration = baseAttributes.baseGreenCreepMoveDur;
</pre>
<p>Now in BossBrownCreep replace the setp of these variables with<br />
:</p>
<pre class="brush:c++">
BaseAttributes* baseAttributes = [BaseAttributes sharedAttributes];
creep.hp = creep.totalHp = baseAttributes.baseBrownCreepHealth;
creep.moveDuration = baseAttributes.baseBrownCreepMoveDur;
</pre>
<p>Phew &#8211; now our creeps will use the variables set in the baseAttributes class. Once again, we do this so that, all game variables can be easily changed from one location, the BaseAttributes class. This also facilitates the possibility of upgrading the creeps during gameplay or between levels.</p>
<p>Next up towers!</p>
<p>Yep we are finally there, we are going to implement the Cannon Tower, with splash damage! First, open the source code and copy the entire contents of Tower.h and Tower.m into your project, in the respective files (replacing any content). Next add the images CannonTurretUpgrade.png, FreezeTurretUpgrade.png and MachineGunTurretUpgrade.png from the source file into your project resources folder.</p>
<p>Take a few moments to look through the code in Tower.m and .h and get your head around it.  Key points:</p>
<ul>
<li>We now have a CannonTower class, it is very similar to the other classes.  In the parent class &#8220;Tower&#8221; we created a number of new variables, then in each of the child classes (MachineGunTower, FreezeTower, CannonTower) we used the data in baseAttributes to set these variables.</li>
<li> Towers need experience to level up. (Experience will increase through successful hits.)</li>
<li> If a Tower has reached its lvlUp limit, a new image, used to indicate that a upgrade is ready is shown replacing the original tower image.</li>
<li> Variables such as tower damage, range and fire rate are set in baseAttributes and are stored in the tower class.</li>
<li> We now send to Projectile, the tower id of its shooting tower.</li>
</ul>
<p>This is a somewhat major over haul, if some of this does not make immediate sense, hopefully it will become apparent shortly. Next we must make a few adjustments to the projectile class, we must add the cannonProjectile class, and we must also allow projectile to hold the tower ID that shot it.</p>
<pre class="brush:c++">//Projectile.h
     @interface Projectile : CCSprite {
          CCSprite *parentTower;
     }

     @property (nonatomic, assign) CCSprite *parentTower;
     + (id)projectile: (id) sender;
     @end

     @interface IceProjectile : Projectile {
     }
     + (id)projectile: (id) sender;
     @end

     @interface CannonProjectile : Projectile {
     }
     + (id)projectile: (id) sender;
     @end
</pre>
<p>In the actual projectile class:</p>
<pre class="brush:c++">
//Projectile.m
#import "Projectile.h"
@implementation Projectile
@synthesize parentTower = parentTower;

+ (id)projectile: (id) sender {
     Projectile *projectile = nil;
     if ((projectile = [[[super alloc]
          initWithFile:@"Projectile.png"] autorelease])) {
               projectile.parentTower = sender;
          }
     return projectile;
}

- (void) dealloc
{
     [super dealloc];
}
@end

@implementation IceProjectile
+ (id)projectile : (id) sender{

     IceProjectile *projectile = nil;
     if ((projectile = [[[super alloc] initWithFile:@"IceProjectile.png"] autorelease])) {
          projectile.parentTower = sender;
     }
     return projectile;
}

- (void) dealloc
{
     [super dealloc];
}
@end

@implementation CannonProjectile
+ (id)projectile : (id) sender{

     CannonProjectile *projectile = nil;
     if ((projectile = [[[super alloc]
          initWithFile:@"CannonProjectile.png"] autorelease])) {
               projectile.parentTower = sender;
     }
     return projectile;
}

- (void) dealloc
{
     [super dealloc];
}
@end</pre>
<p>Oh, and remember to add the &#8220;CannonProjectile.png&#8221; from the source file too! Holding the parentTower id in the projectileClass is very useful, especially for tower experience. One final thing, go to Tutorialscene.m and find the AddTower method.</p>
<p>for switch (towerTag) case 3: change the call to:</p>
<pre class="brush:c++">target = [CannonTower tower];</pre>
<p>Run the program now, make sure that the Cannon is firing the correct projectile, and there are no errors. Making it go Boom, oh and gaining experience <img src='http://www.iphonegametutorials.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  Both of these functions are implemented within the &#8220;upgrade&#8221; function in TutorialScene.m.</p>
<p>Find the statement</p>
<pre class="brush:c++">
if (CGRectIntersectsRect(projectileRect, targetRect))
{
     //Code
}
</pre>
<p>and replace it with the following:</p>
<pre class="brush:c++">

if (CGRectIntersectsRect(projectileRect, targetRect)) {
     [projectilesToDelete addObject:projectile];

     Creep *creep = (Creep *)target;
     Creep *thisCreep;

     Tower *parentTower = (Tower *) projectile.parentTower;
     int thisHitDamage;

     CGRect splashRect;
     switch (projectile.tag) {
     case 1:
          thisHitDamage = (rand()%baseAttributes.baseMGDamageRandom)+parentTower.damageMin;
          creep.hp -= thisHitDamage;
          parentTower.experience += thisHitDamage;
     break;

     case 2:
          thisHitDamage = (rand()%baseAttributes.baseFDamageRandom)+parentTower.damageMin;
          creep.hp -= thisHitDamage;
          parentTower.experience += thisHitDamage;

          id actionFreeze = [CCMoveTo actionWithDuration:parentTower.freezeDur position:creep.position];
          id actionMoveResume = [CCCallFuncN actionWithTarget:self selector:@selector(ResumePath:)];
          [creep stopAllActions];
          [creep runAction:[CCSequence actions:actionFreeze, actionMoveResume, nil]];
     break;

     case 3:
          thisHitDamage = (rand()%baseAttributes.baseFDamageRandom)+parentTower.damageMin;
          parentTower.experience += thisHitDamage;
          splashRect = CGRectMake(projectile.position.x - (parentTower.splashDist), projectile.position.y - (parentTower.splashDist), (parentTower.splashDist*2), (parentTower.splashDist*2));

          for (CCSprite *target in m._targets) {
               CGRect thistargetRect = CGRectMake(target.position.x - (target.contentSize.width/2), target.position.y - (target.contentSize.height/2), target.contentSize.width, target.contentSize.height);
               if (CGRectIntersectsRect(splashRect, thistargetRect)) {
                    thisCreep = (Creep *) target;
                    thisCreep.hp -= thisHitDamage;

                    if (thisCreep.hp <= 0) {
                         [targetsToDelete addObject:target];
                         [gameHUD updateResources: rand()% (baseAttributes.baseMoneyDropped)];

                         [self removeChild:thisCreep.healthBar cleanup:YES];
                    }
               }
          }
     break;

     default:
     break;
     }

     if (creep.hp <= 0) {
          [targetsToDelete addObject:target];
          [gameHUD updateResources: rand()%(baseAttributes.baseMoneyDropped)];
          [self removeChild:creep.healthBar cleanup:YES];
     }
     break;
}</pre>
<p>Bam Done!  Whats new? :</p>
<ul>
<li>We capture the parentTower of the projectile so that we can gain access to its variables.</li>
<li> The projectile.tag if statements have been replaced with a more efficient switch statement.</li>
<li> The hit damage is affected by a random amount (located in baseAttributes for each tower individually) to emulate critical/glancing hits.</li>
<li> The parent towers experience is increased by the amount of damage done.</ul>
<li> When a creep dies, it drops a random amount of money which is added to resources.</li>
<li> Cannon Projectile creates splash damage.</li>
</ul>
<p>Its probably worth just talking about splash damage in a little bit more detail. When a Cannon projectile hits a creep projectile we first decided how much damage it will do. We then create a Rect around this projectile, with a side length of twice the splashDistance (so splashDistance is the “radius”). We then run through the all the creeps again, and see if any of them fall within the SplashRect. Any that do fall within this rect take damage and if their hp &lt;= 0 then they are removed.</p>
<p>Run this and we have a working program with 3 tower types, 2 creep classes and our game variables are all stored within one place.  Next up, we're going to give our game an ending and maybe a few other goodies as well!</p>
<p>Yours,<br />
Aiden Fry<br />
iPhone Game Tutorials Contributor</p>
<p>Aiden Fry is a recent graduate, working to get into the games industry. He is a games programmer with a special interest in audio programming. Please check out his website <a href="http://aidenfry.tk" target="_blank">aidenfry.tk</a> to see some of his work.</p>

<div class="jwsharethis">
Share this: 
<br />
<a href="mailto:?subject=How%20to%20Build%20a%20Tower%20Defense%20Game%20for%20the%20iPhone%20%E2%80%93%20Part%208B%20%E2%80%93%20Tower%20Powers&amp;body=http%3A%2F%2Fwww.iphonegametutorials.com%2F2012%2F02%2F16%2Fhow-to-build-a-tower-defense-game-for-the-iphone-part-8b-tower-powers-2%2F">
<img src="http://www.iphonegametutorials.com/wp-content/plugins/jw-share-this/email.png" alt="Share this page via Email" />
</a>
<a target="_blank" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.iphonegametutorials.com%2F2012%2F02%2F16%2Fhow-to-build-a-tower-defense-game-for-the-iphone-part-8b-tower-powers-2%2F&amp;title=How+to+Build+a+Tower+Defense+Game+for+the+iPhone+%E2%80%93+Part+8B+%E2%80%93+Tower+Powers">
<img src="http://www.iphonegametutorials.com/wp-content/plugins/jw-share-this/su.png" alt="Share this page via Stumble Upon" />
</a>
<a target="_blank" href="http://digg.com/submit?url=http%3A%2F%2Fwww.iphonegametutorials.com%2F2012%2F02%2F16%2Fhow-to-build-a-tower-defense-game-for-the-iphone-part-8b-tower-powers-2%2F&amp;title=How+to+Build+a+Tower+Defense+Game+for+the+iPhone+%E2%80%93+Part+8B+%E2%80%93+Tower+Powers">
<img src="http://www.iphonegametutorials.com/wp-content/plugins/jw-share-this/digg.png" alt="Share this page via Digg this" />
</a>
<a target="_blank" href="http://www.facebook.com/sharer.php?u=http%3A%2F%2Fwww.iphonegametutorials.com%2F2012%2F02%2F16%2Fhow-to-build-a-tower-defense-game-for-the-iphone-part-8b-tower-powers-2%2F&amp;t=How+to+Build+a+Tower+Defense+Game+for+the+iPhone+%E2%80%93+Part+8B+%E2%80%93+Tower+Powers">
<img src="http://www.iphonegametutorials.com/wp-content/plugins/jw-share-this/fb.png" alt="Share this page via Facebook" />
</a>
<a target="_blank" href="http://twitter.com/intent/tweet?text=I+like+http%3A%2F%2Fwww.iphonegametutorials.com%2F2012%2F02%2F16%2Fhow-to-build-a-tower-defense-game-for-the-iphone-part-8b-tower-powers-2%2F&amp;title=How+to+Build+a+Tower+Defense+Game+for+the+iPhone+%E2%80%93+Part+8B+%E2%80%93+Tower+Powers">
<img src="http://www.iphonegametutorials.com/wp-content/plugins/jw-share-this/twitter.png" alt="Share this page via Twitter" />
</a>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.iphonegametutorials.com/2012/02/16/how-to-build-a-tower-defense-game-for-the-iphone-part-8b-tower-powers-2/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>How to Build a Tower Defense Game for the iPhone – Part 8 – Some early spring cleaning</title>
		<link>http://www.iphonegametutorials.com/2012/02/12/how-to-build-a-tower-defense-game-for-the-iphone-part-8-some-early-spring-cleaning/</link>
		<comments>http://www.iphonegametutorials.com/2012/02/12/how-to-build-a-tower-defense-game-for-the-iphone-part-8-some-early-spring-cleaning/#comments</comments>
		<pubDate>Sun, 12 Feb 2012 04:45:46 +0000</pubDate>
		<dc:creator>Aiden Fry</dc:creator>
				<category><![CDATA[Advanced]]></category>
		<category><![CDATA[Cocos2d]]></category>
		<category><![CDATA[Tower Defense]]></category>
		<category><![CDATA[actionWithTarget]]></category>
		<category><![CDATA[addChild]]></category>
		<category><![CDATA[addObject]]></category>
		<category><![CDATA[CCLabel]]></category>
		<category><![CDATA[CCSprite]]></category>
		<category><![CDATA[CGRectContainsPoint]]></category>
		<category><![CDATA[CGRectMake]]></category>
		<category><![CDATA[Download]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[source]]></category>
		<category><![CDATA[source code]]></category>
		<category><![CDATA[tower defense]]></category>
		<category><![CDATA[tower defense game]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[Tutorials]]></category>

		<guid isPermaLink="false">http://www.iphonegametutorials.com/?p=717</guid>
		<description><![CDATA[Ok, so a few issues have been raised over the course of this tutorial series and I have tried to answer them as we go in the comments section. However I feel that we could do with a good clean up of our code. In this tutorial we will be doing a little spring cleaning [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.iphonegametutorials.com/wp-content/uploads/2012/02/tut8.png"><img src="http://www.iphonegametutorials.com/wp-content/uploads/2012/02/tut8-300x154.png" alt="" title="tut8" width="300" height="154" class="alignleft size-medium wp-image-731" /></a>Ok, so a few issues have been raised over the course of this tutorial series and I have tried to answer them as we go in the comments section.  However I feel that we could do with a good clean up of our code. In this tutorial we will be doing a little spring cleaning of the code and preparing for future improvements such as, Splash damage tower, Upgrading towers (real time), Upgrading/Personalizing army stats (between rounds).</p>
<p>Firstly, problem solving:<br />
After downloading the source code, the first thing that anyone with a developers license should see is that when you run the game those pesky lines / tile artifact issues have been solved. This was done by a small edit to the file CCSprite.m, big thank you to DreemLife for your efforts with sorting out this issue. If you are experiencing those tile artifacts in this project, the previous tutorials, or for any other project, then replace your CCsprite.m file with the one from the source code in this project.</p>
<p>Tower shenanigans:<br />
Sometimes after a Creep has been removed, a Tower will send a projectile towards (0,0). This is because we have removed the towers target, without telling it not to shoot.  Simply add the following to tower.m -> FinishedFiring method. (This will need to be done for all Tower classes)</p>
<p><span id="more-717"></span></p>
<pre class="brush:c++">
-(void)finishFiring {
if (self.target != NULL) {
// Keep all pre-existing code
} }
</pre>
<p>Next, I would like our towers to target one creep, until it is either dead or out of range, before targeting a new creep, However at the moment only the nearest creep is targeted.  Add the following method to each tower class</p>
<pre class="brush:c++">
-(void)checkTarget {
double curDistance = ccpDistance(self.position, self.target.position);
if (self.target.hp <= 0 || curDistance > self.range){
self.target = [self getClosestTarget]; } }
</pre>
<p>Adding this call to the </p>
<pre class="brush:c++">
+(id) tower methods. [tower schedule:@selector(checkTarget) interval:0.5];
and change the call to getClosestTarget in TowerUpdate methods
-(void)towerLogic:(ccTime)dt {
if (self.target == nil) {
self.target = [self getClosestTarget];
}
//All other code stays the same
}
</pre>
<p>Increasing the Tower Rotate speed &#038; bullet speed, It just seems nicer! Staying in the towerLogic method, change the rotateSpeed to: </p>
<pre class="brush:c++">
float rotateSpeed = 0.25 / M_PI; // 1/4 second to rotate 180 degrees and in finished
</pre>
<p>and the firing delta to: </p>
<pre class="brush:c++">
ccTime delta = 0.5;
</pre>
<p>Run this and we should see our game is behaving a little better.  One more thing is that we are currently able to build two towers on the same location. This needs changing. In tutorialsScene.m replace canBuild&#8230; method with the following.</p>
<pre class="brush:c++">
-(BOOL) canBuildOnTilePosition:(CGPoint) pos
{
     CGPoint towerLoc = [self tileCoordForPosition: pos];
     int tileGid = [self.background tileGIDAt:towerLoc];
     NSDictionary *props = [self.tileMap propertiesForGID:tileGid];
     NSString *type = [props valueForKey:@"buildable"];

     bool occupied = NO;
     DataModel *m = [DataModel getModel];

     for (Tower *tower in m._towers) {
          CGRect towerRect = CGRectMake(tower.position.x - (tower.contentSize.width/2), tower.position.y - (tower.contentSize.height/2), tower.contentSize.width, tower.contentSize.height);
          if (CGRectContainsPoint(towerRect, pos)) {
               occupied = YES;
          }
     } 

     if([type isEqualToString: @"1"] &#038;&#038; occupied == NO) {
          return YES;
     }
     return NO;
}
</pre>
<p>Similarly in addTower add the following before the switch statement</p>
<pre class="brush:c++">
-(void)addTower: (CGPoint)pos: (int)towerTag {
     DataModel *m = [DataModel getModel];
     Tower *target = nil;
     CGPoint towerLoc = [self tileCoordForPosition: pos];

     int tileGid = [self.background tileGIDAt:towerLoc];
     NSDictionary *props = [self.tileMap propertiesForGID:tileGid];
     NSString *type = [props valueForKey:@"buildable"];

     bool occupied = NO; 

     for (Tower *tower in m._towers) {
          CGRect towerRect = CGRectMake(tower.position.x - (tower.contentSize.width/2), tower.position.y - (tower.contentSize.height/2), tower.contentSize.width, tower.contentSize.height);
          if (CGRectContainsPoint(towerRect, pos)) {
               occupied = YES;
          }
     } 

     if([type isEqualToString: @"1"] &#038;&#038; occupied == NO) {
          switch (towerTag) {
               //Leave all other code the same.
</pre>
<p>One improvement, for better player usability, when placing towers the player can not really see the tower as their finger is in the way. lets move the sprite up a little so we can see it while placing the tower.  First, go into GameHUD and find the CCtouchBegan method where we set newsprite.position, replace it with the following.</p>
<pre class="brush:c++">
newSprite.position = ccpAdd(sprite.position, ccp(0, 50));
</pre>
<p>Now open TutorialScene.m and find the canBuildonTilePosition method an the following at the very top of the method</p>
<pre class="brush:c++">
pos = ccpAdd(pos, ccp(0, 50));
</pre>
<p>similarly add the same code to the top of the addTower method. Run and check that this works. </p>
<p>Creeps:<br />
As you may have noticed, the creeps speed up and slow down depending on the distance between waypoints. Now, we will fix this so that Creeps move at the same speed all the way around the map.  In the Creeps.m file we will need to following method to the Creep implementation:</p>
<pre class="brush:c++">
(float) moveDurScale {
     DataModel *m = [DataModel getModel]; 

     WayPoint *waypoint0 = (WayPoint *) [m._waypoints objectAtIndex:0];
     WayPoint *waypoint1 = (WayPoint *) [m._waypoints objectAtIndex:1]; 

     firstDistance = ccpDistance(waypoint0.position, waypoint1.position);
     WayPoint *waypoint2 = (WayPoint *) [m._waypoints objectAtIndex:(self.curWaypoint-1)];
     WayPoint *waypoint3 = (WayPoint *) [m._waypoints objectAtIndex:(self.curWaypoint)]; 

     float thisDistance = ccpDistance(waypoint2.position, waypoint3.position);
     float moveScale = thisDistance/firstDistance; return (self.moveDuration * moveScale);
}

//Add to Creep.h interface float firstDistance;
(float) moveDurScale;
</pre>
<p>What this does is to represent the current distance as a fraction of the first distance (between waypoints). This fraction is then used to scale the moveDuration. EG if a distance is half as long as the first distance, the move duration is half that of the first duration. Now to implement this new method, go into TutorialScene.m and find the FollowPath method and</p>
<p>replace:</p>
<pre class="brush:c++">
int moveDuration = creep.moveDuration;
</pre>
<p>with:</p>
<pre class="brush:c++">
float moveDuration = [creep moveDurScale];
</pre>
<p>Finally, find ResumePath method and replace:</p>
<pre class="brush:c++">
float moveDuration = creep.moveDuration * distFraction;
</pre>
<p>with: </p>
<pre class="brush:c++">
float durScale = [creep moveDurScale];
float moveDuration = durScale * distFraction;
</pre>
<p>There, Build this and things should start looking even better and behaving as we would expect.</p>
<p>New Additions:<br />
Boss Creep:</p>
<p>Add the following class to Creep.m</p>
<pre class="brush:c++">
@implementation BossBrownCreep

+ (id)creep {
     BossBrownCreep *creep = nil;

     if ((creep = [[[super alloc] initWithFile:@"Enemy3.png"] autorelease])) {
          creep.hp = creep.initHp = 500;
          creep.moveDuration = 10;
          creep.curWaypoint = 0; [creep schedule:@selector(creepLogic:) interval:0.2];

          [creep schedule:@selector(healthBarLogic:)];
     } 

     return creep;
}
@end
</pre>
<p>and add the class definition to the Creep.h.  Using the BossCreep. In wave.m add the BrownCreeps to this method in exactly the same way as the Green or Red creeps. Then remember to update the wave.h file for this function and add the variables for brownCreeps. Next we will open tutorial.m and change our addWaves method so that it looks something like this:</p>
<pre class="brush:c++">
wave = [[Wave alloc] initWithCreep:[FastRedCreep creep] SpawnRate:1.0 RedCreeps:5
GreenCreeps:0 BrownCreeps:0];
</pre>
<p>Now we can set the brown creeps as we like, I have reserved them for wave 5 the boss wave.  Replace the addTarget method with the following</p>
<pre class="brush:c++">

-(void)addTarget {
     DataModel *m = [DataModel getModel];
     Wave * wave = [self getCurrentWave];

     if (wave.redCreeps <= 0 &#038;&#038; wave.greenCreeps <= 0 &#038;&#038; wave.brownCreeps <= 0) {
          return; //
     } 

     //wave.totalCreeps--;
     Creep *target = nil;
     int creepChoice = (arc4random() % 3);

     int layer;
     switch (creepChoice) {
          case 0:
               if (wave.redCreeps > 0) {
                    target = [FastRedCreep creep];
                    target.tag = 1;
                    wave.redCreeps--;
                    layer = 1;
               }
               else {
                    [self addTarget];
                    return;
               }
          break;

          case 1:
               if (wave.greenCreeps >0) {
                    target = [StrongGreenCreep creep];
                    target.tag = 2;
                    wave.greenCreeps--;
                    layer = 1;
               }
               else {
                    [self addTarget];
                    return;
               }
          break;

          case 2:
               if (wave.brownCreeps >0) {
                    target = [BossBrownCreep creep];
                    target.tag = 3;
                    wave.brownCreeps--;
                    layer = 2;
               }
               else{
                    [self addTarget];
                    return;
               }
          break;

          default:
          break;
     } 

     WayPoint *waypoint = [target getCurrentWaypoint];

     target.position = waypoint.position;
     waypoint = [target getNextWaypoint ];

     [self addChild:target z:layer];
     float moveDuration = target.moveDuration;
     id actionMove = [CCMoveTo actionWithDuration:moveDuration position:waypoint.position];
     id actionMoveDone = [CCCallFuncN actionWithTarget:self selector:@selector(FollowPath:)];

     [target runAction:[CCSequence actions:actionMove, actionMoveDone, nil]]; // Add to targets array
     [m._targets addObject:target];
     return;
}
</pre>
<p>The last thing to do is to find our update method, and look at the bottom where we search to see if the wave has ended. Replace the if statement with the following</p>
<pre class="brush:c++">
if ([m._targets count] ==0 &#038;&#038; wave.redCreeps <= 0 &#038;&#038; wave.greenCreeps <= 0 &#038;&#038; wave.brownCreeps <= 0) {
</pre>
<p>Run this and we now will have some harder boss creeps, use them wisely! <img src='http://www.iphonegametutorials.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' />  Creep health Bars:  I thought it would be good to include health bars above the creeps so that we are able to see how much damage each creep is has taken.  Add a CCProgressTimer and a new int to creep.h</p>
<pre class="brush:c++">
CCProgressTimer *healthBar;
int _totalHp;
</pre>
<p>Make sure to also add the needed @property and @synthesize these variables as well, then in Creep.M under creepLogic add the following method:</p>
<pre class="brush:c++">
-(void)healthBarLogic:(ccTime)dt {

     //Update health bar pos and percentage.
     healthBar.position = ccp(self.position.x, (self.position.y+20));
     healthBar.percentage = ((float)self.hp/(float)self.totalHp) *100;

     if (healthBar.percentage <= 0) {
          [self removeChild:healthBar cleanup:YES];
     }
}
</pre>
<p>This simply keeps the health bar placed above the creep, and updates the bar.percentage by the creeps hp.  Add these calls in both +(id)creep methods </p>
<pre class="brush:c++">
creep.hp = creep.totalHp = setRedHp;
[creep schedule:@selector(healthBarLogic:)];
</pre>
<p>Finally to implement these health bars add the following to addTarget in TutorialScene.m</p>
<pre class="brush:c++">
//Under [self addChild:target z:1];
target.healthBar = [CCProgressTimer progressWithFile:@"health_bar_red.png"];
target.healthBar.type = kCCProgressTimerTypeHorizontalBarLR;
target.healthBar.percentage = 100;
[target.healthBar setScale:0.1];
target.healthBar.position = ccp(target.position.x,(target.position.y+20));

[self addChild:target.healthBar z:3];
</pre>
<p>Finally go down to upgrade method and add the following when we check to see the is the creep is dead.</p>
<pre class="brush:c++">
if (creep.hp <= 0) {
     [targetsToDelete addObject:target];
     [gameHUD updateResources:1];
     [self removeChild:creep.healthBar cleanup:YES];//Add this
}
</pre>
<p>There we have it, health bars <img src='http://www.iphonegametutorials.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  Waves: They are a little fast no?!<br />
Just add the following method to TutorialScene.m:</p>
<pre class="brush:c++">
-(void)waveWait {
     [self unschedule:@selector(waveWait)];
     [self getNextWave]; [gameHUD updateWaveCount];
}
</pre>
<p>Then in update, where we call to [self getNextWave] and [gameHUD updateWaveCount] change this to:</p>
<pre class="brush:c++">
[self schedule:@selector(waveWait) interval:3.0];
</pre>
<p>Now there is a small gap between the waves, lets tell the player this!  Open gameHUD.h and add the following variable:</p>
<pre class="brush:c++">
 CCLabelTTF *newWaveLabel;
</pre>
<p>Now open gameHUD.m and add the following</p>
<pre class="brush:c++">
//Add to init
// Set up new Wave label
newWaveLabel = [CCLabelTTF labelWithString:@"" dimensions:CGSizeMake(300, 50)
alignment:UITextAlignmentRight fontName:@"TrebuchetMS-Bold" fontSize:30];
newWaveLabel.position = ccp((winSize.width/2)-20, (winSize.height/2)+30);
newWaveLabel.color = ccc3(255,50,50); [self addChild:newWaveLabel z:1];

//add new methods &#038; define them in the header file
-(void) newWaveApproaching {
     [newWaveLabel setString:[NSString stringWithFormat: @"HERE THEY COME!"]];
}

-(void) newWaveApproachingEnd {
     [newWaveLabel setString:[NSString stringWithFormat: @" "]];
}
</pre>
<p>Now, call newWaveApproaching when we call waveWait, and call newWaveApproachingEnd from the actual waveWait method. (both in tutorial.m) Finally, finally! I don’t like the fact that when the game begins the first wave is instantly spawned, lets use the waveWait method here too.  Open tutorial.m and find the addWaves and simply add a blank wave at the beginning.</p>
<pre class="brush:c++">
Wave *wave = nil;
wave = [[Wave alloc] initWithCreep:[FastRedCreep creep] SpawnRate:1.0 RedCreeps:0 GreenCreeps:0];
[m._waves addObject:wave];
</pre>
<p>Now two quick adjustments need to be made, in getNextWave, change our maximum wave count to be 6 (or one more that it previously was), and go into gameHUD.m, in the init method change the starting waveCount to be</p>
<pre class="brush:c++">
waveCount = 0;
</pre>
<p>That's enough for this particular spring clean, however check back soon for part 8B where we'll be discussing more tower types including a new baseAttributes class.</p>
<p>Yours,<br />
Aiden Fry<br />
iPhone Game Tutorials Contributor</p>
<p>Aiden Fry is a recent graduate, working to get into the games industry. He is a games programmer with a special interest in audio programming. Please check out his website <a href="http://aidenfry.tk" target="_blank">aidenfry.tk</a> to see some of his work.</p>

<div class="jwsharethis">
Share this: 
<br />
<a href="mailto:?subject=How%20to%20Build%20a%20Tower%20Defense%20Game%20for%20the%20iPhone%20%E2%80%93%20Part%208%20%E2%80%93%20Some%20early%20spring%20cleaning&amp;body=http%3A%2F%2Fwww.iphonegametutorials.com%2F2012%2F02%2F12%2Fhow-to-build-a-tower-defense-game-for-the-iphone-part-8-some-early-spring-cleaning%2F">
<img src="http://www.iphonegametutorials.com/wp-content/plugins/jw-share-this/email.png" alt="Share this page via Email" />
</a>
<a target="_blank" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.iphonegametutorials.com%2F2012%2F02%2F12%2Fhow-to-build-a-tower-defense-game-for-the-iphone-part-8-some-early-spring-cleaning%2F&amp;title=How+to+Build+a+Tower+Defense+Game+for+the+iPhone+%E2%80%93+Part+8+%E2%80%93+Some+early+spring+cleaning">
<img src="http://www.iphonegametutorials.com/wp-content/plugins/jw-share-this/su.png" alt="Share this page via Stumble Upon" />
</a>
<a target="_blank" href="http://digg.com/submit?url=http%3A%2F%2Fwww.iphonegametutorials.com%2F2012%2F02%2F12%2Fhow-to-build-a-tower-defense-game-for-the-iphone-part-8-some-early-spring-cleaning%2F&amp;title=How+to+Build+a+Tower+Defense+Game+for+the+iPhone+%E2%80%93+Part+8+%E2%80%93+Some+early+spring+cleaning">
<img src="http://www.iphonegametutorials.com/wp-content/plugins/jw-share-this/digg.png" alt="Share this page via Digg this" />
</a>
<a target="_blank" href="http://www.facebook.com/sharer.php?u=http%3A%2F%2Fwww.iphonegametutorials.com%2F2012%2F02%2F12%2Fhow-to-build-a-tower-defense-game-for-the-iphone-part-8-some-early-spring-cleaning%2F&amp;t=How+to+Build+a+Tower+Defense+Game+for+the+iPhone+%E2%80%93+Part+8+%E2%80%93+Some+early+spring+cleaning">
<img src="http://www.iphonegametutorials.com/wp-content/plugins/jw-share-this/fb.png" alt="Share this page via Facebook" />
</a>
<a target="_blank" href="http://twitter.com/intent/tweet?text=I+like+http%3A%2F%2Fwww.iphonegametutorials.com%2F2012%2F02%2F12%2Fhow-to-build-a-tower-defense-game-for-the-iphone-part-8-some-early-spring-cleaning%2F&amp;title=How+to+Build+a+Tower+Defense+Game+for+the+iPhone+%E2%80%93+Part+8+%E2%80%93+Some+early+spring+cleaning">
<img src="http://www.iphonegametutorials.com/wp-content/plugins/jw-share-this/twitter.png" alt="Share this page via Twitter" />
</a>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.iphonegametutorials.com/2012/02/12/how-to-build-a-tower-defense-game-for-the-iphone-part-8-some-early-spring-cleaning/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>How to Build a Tower Defense Game for the iPhone &#8211; Part 7 &#8211; Money and Health</title>
		<link>http://www.iphonegametutorials.com/2012/01/24/how-to-build-a-tower-defense-game-for-the-iphone-part-7-money-and-health/</link>
		<comments>http://www.iphonegametutorials.com/2012/01/24/how-to-build-a-tower-defense-game-for-the-iphone-part-7-money-and-health/#comments</comments>
		<pubDate>Tue, 24 Jan 2012 18:34:15 +0000</pubDate>
		<dc:creator>Aiden Fry</dc:creator>
				<category><![CDATA[Advanced]]></category>
		<category><![CDATA[Cocos2d]]></category>
		<category><![CDATA[Tower Defense]]></category>
		<category><![CDATA[Download]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[source code]]></category>
		<category><![CDATA[tower defense]]></category>
		<category><![CDATA[tower defense game]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[Tutorials]]></category>

		<guid isPermaLink="false">http://www.iphonegametutorials.com/?p=701</guid>
		<description><![CDATA[Hello, and welcome to part 7 of the Tower Defense Tutorial Series. &#8211; Money and Health! In this tutorial we will incorporate “money” into the game so that towers cost the player, and the amount of money available will slowly increase over time. We shall also be incorporating base health bar into the game so [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.iphonegametutorials.com/wp-content/uploads/2012/01/BaseHealthandMoney.png"><img src="http://www.iphonegametutorials.com/wp-content/uploads/2012/01/BaseHealthandMoney-300x152.png" alt="" title="BaseHealthandMoney" width="300" height="152" class="alignleft size-medium wp-image-709" /></a>Hello, and welcome to part 7 of the Tower Defense Tutorial Series. &#8211; Money and Health!</p>
<p>In this tutorial we will incorporate “money” into the game so that towers cost the player, and the amount of money available will slowly increase over time. We shall also be incorporating base health bar into the game so we can ultimately have a game over. This particular tutorial focuses primarily on implementing dynamic labels and images, and the game logic behind them, as part of the gameHUD. </p>
<p>When adding labels to gameHUD.m the ﬁrst thing we need to do is to decide upon what we want to display, in this case; Money count, abase health label and a base health bar, a wave count, and the prices of each tower. </p>
<p>Source code after the break&#8230;<br />
<span id="more-701"></span></p>
<p>First things first, if you want to just see everything in action, here is the source code: <a href="http://www.iphonegametutorials.com/wp-content/uploads/2012/01/TowerDefensePart7.zip">Tower Defense Part 7</a>.</p>
<p>In gameHUD.m ﬁnd the init function. Right before the line:</p>
<pre class="brush:c++">
[[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES];
</pre>
<p>paste the following code: </p>
<pre class="brush:c++">
// Set up Resources and Resource label
resources = 100;
self->resourceLabel = [CCLabelTTF labelWithString:@"Money $100" dimensions:CGSizeMake(150, 25) alignment:UITextAlignmentRight fontName:@"Marker Felt" fontSize:20]; 

resourceLabel.position = ccp(30, (winSize.height -15));
resourceLabel.color = ccc3(255,80,20);
[self addChild:resourceLabel z:1]; 

// Set up BaseHplabel
CCLabelTTF *baseHpLabel = [CCLabelTTF labelWithString:@"Base Health" dimensions:CGSizeMake(150, 25) alignment:UITextAlignmentRight fontName:@"Marker Felt" fontSize:20];

baseHpLabel.position = ccp((winSize.width -185), (winSize.height -15));
baseHpLabel.color = ccc3(255,80,20);
[self addChild:baseHpLabel z:1]; 

// Set up wavecount label
waveCount = 1;
self->waveCountLabel = [CCLabelTTF labelWithString:@"Wave 1" dimensions:CGSizeMake(150, 25) alignment:UITextAlignmentRight fontName:@"Marker Felt" fontSize:20]; 

waveCountLabel.position = ccp(((winSize.width/2) -80), (winSize.height -15));
waveCountLabel.color = ccc3(100,0,100);
[self addChild:waveCountLabel z:1];
</pre>
<p>The ﬁrst three blocks of code, where we set up the wave count, resources (money) and base health labels should be fairly simple, however if you are unfamiliar with labels then feel free to take a few moments to understand the code above.<br />
The interesting code comes next when implementing the health bar. First download the Red and Green health bar images here [insert link] and then import them to your resources folder in Xcode. </p>
<p>Next copy the following code and place it bellow the label setup shown above. </p>
<pre class="brush:c++">
//Set up health Bar
baseHpPercentage = 100;
self->healthBar = [CCProgressTimer progressWithFile:@"health_bar_green.png"];
self->healthBar.type = kCCProgressTimerTypeHorizontalBarLR;
self->healthBar.percentage = baseHpPercentage;
[self->healthBar setScale:0.5];
self->healthBar.position = ccp(winSize.width -55, winSize.height -15);
[self addChild:healthBar z:1];
</pre>
<p>We are using a “CCProgresstimer” to show the health bar image, we chose this because a ProgressTimer is able to show percentages of an image. We chose the type horizontalBarLR because the health bar image is a horizontal bar, and we wish (when the base takes damage) to decrease the health bar starting from the right end (100% health), moving towards the left end (0% health). We then set the percentage to be 100, as we start with full health. We also scale the image by half for aesthetic reasons, and set the position of the bar. </p>
<p>The last thing that we need to do, is to set labels to show the “price” of each tower. </p>
<p>Find the for statement which places the tower images onto the gameHUD, then replace it with the following. </p>
<pre class="brush:c++">
for(int i = 0; i < images.count; ++i) {
      NSString *image = [images objectAtIndex:i];
      CCSprite *sprite = [CCSprite spriteWithFile:image];
      float offsetFraction = ((float)(i+1))/(images.count+1);
      sprite.position = ccp(winSize.width*offsetFraction, 35);
      sprite.tag = i+1; printf("tag %i", sprite.tag);
      [self addChild:sprite];
      [movableSprites addObject:sprite]; 

      //Set up and place towerCost labels
      CCLabelTTF *towerCost = [CCLabelTTF labelWithString:@"$" fontName:@"Marker Felt" fontSize:10];
      towerCost.position = ccp(winSize.width*offsetFraction, 15);
      towerCost.color = ccc3(0, 0, 0);
      [self addChild:towerCost z:1]; 

      //Set cost values
      switch (i) {
            case 0:
                  [towerCost setString:[NSString stringWithFormat:@"$ 25]];
            break; 

            case 1:
                  [towerCost setString:[NSString stringWithFormat:@"$ 35”]];
            break; 

            case 2:
                  [towerCost setString:[NSString stringWithFormat:@"$ 25]];
            break; 

            case 3:
                  [towerCost setString:[NSString stringWithFormat:@"$ 25]];
            break; 

            default:
            break;
      }
}
</pre>
<p>This simply places a price label slightly bellow the tower image, with a separate price for each tower image. </p>
<p>One final thing to do is to set up the variables involved in the dynamic labels. Add the following variables into the declaration of gameHUD.h:</p>
<p>int resources; </p>
<pre class="brush:c++">
      CCLabelTTF *resourceLabel;
      CCLabelTTF *waveCountLabel;
      float baseHpPercentage;
      CCProgressTimer *healthBar;
} 

@property (nonatomic, assign) int resources;
@property (nonatomic, assign) float baseHpPercentage;
</pre>
<p>and in gameHUD.m add the following:</p>
<pre class="brush:c++">
@synthesize resources = resources;
@synthesize baseHpPercentage = baseHpPercentage; 

int waveCount;
</pre>
<p>Next we will add the logic behind these labels to make them informative to the player and meaningful within the game. </p>
<p>Adding Towers: Removing Resources.<br />
Go into gameHUD.m and add the following functions (remember to add the headers too). </p>
<pre class="brush:c++">
-(void) updateResources:(int)amount {
      resources += amount;
      [self->resourceLabel setString:[NSString stringWithFormat: @"Money $ %i",resources]];
} 

-(void) updateResourcesNom {
      resources += 1;
      [self->resourceLabel setString:[NSString stringWithFormat: @"Money $ %i",resources]];
}
</pre>
<p>We can now use this function to update the amount of resources, then place the new number on screen. Next go into TutorialScene.m and find the addTower function. Replace the switch statement (towerTag) with the following: </p>
<pre class="brush:c++">
switch (towerTag) {
      case 1:
            if (gameHUD.resources >= 25) {
                  target = [MachineGunTower tower];
                  [gameHUD updateResources:-25];
            } else return;
      break; 

      case 2:
            if (gameHUD.resources >= 35) {
                  target = [FreezeTower tower];
                  [gameHUD updateResources:-35];
             } else return;
      break; 

      case 3:
            if (gameHUD.resources >= 25) {
                  target = [MachineGunTower tower];
                  [gameHUD updateResources:-25];
             } else return;
      break; 

      case 4:
            if (gameHUD.resources >= 25) {
                  target = [MachineGunTower tower];
                  [gameHUD updateResources:-25];
            } else return;
      break; 

      default:
      break; 

}
</pre>
<p>What this does, is to check to see if there is enough resources available, if there is then it creates the tower selected and removes the cost of the tower from resources. </p>
<p>Next, Increasing the Resources available. There are two ways which the player can increase their money.<br />
1: Money increases over time.<br />
2: Gain money from killing creeps. We will implement both methods, starting with gaining money from killing creeps, go to -update and find where our creep collisions are being detected. When a creep’s health drops below 0 (a creep dies) we add one to the resources total eg: </p>
<pre class="brush:c++">
(creep.hp <= 0) {
      [targetsToDelete addObject:target];
      [gameHUD updateResources:1];
}
</pre>
<p>Next, to increase money over time find the init function of TutorialScene and add the following after the declaration of gameHUD</p>
<p>[gameHUD schedule:@selector(updateResourcesNom) interval: 2.0]; </p>
<p>This will add 1 resource ever two seconds. </p>
<p>Run and test this, and we should have fully operational resources/money functionality. </p>
<p>Next, we need to change the base health when a creep reaches the end of its path. Add the following function to gameHUD.m (&#038; the header). </p>
<pre class="brush:c++">
-(void) updateBaseHp:(int)amount {
      baseHpPercentage += amount; 

      if (baseHpPercentage <= 25) {
            [self->healthBar setSprite:[CCSprite spriteWithFile:@"health_bar_red.png"]];
            [self->healthBar setScale:0.5];
      } 

      if (baseHpPercentage <= 0) {
            //Game Over Scenario
            printf("Game Over\n"); 

            //Implement Game Over Scenario
      }

      [self->healthBar setPercentage:baseHpPercentage]; }
</pre>
<p>So, what this does is to update the baseHpPercentage by a given amount. If the baseHp falls below 25% then we change the image to the red health bar, then in the baseHp falls below (or equal to) 0 we have reached game over (at the moment just a printf message but we shall work on this next tutorial). Then after these checks we update the image bar to reveal the baseHpPercentage. Now, open Creep.m and find the getNextWaypoint function. In this function we check to see if the creep is at the last waypoint, if it is we delete the creep. After we delete the creep add the following code. </p>
<pre class="brush:c++">
gameHUD = [GameHUD sharedHUD]; 

if (gameHUD.baseHpPercentage > 0) {
      [gameHUD updateBaseHp:-10];
}
</pre>
<p>This means that the baseHp will decrease by 10 for each creep that “hits” it. Run and test this code, we should see the health bar be affected by the creeps and change color when low on health. </p>
<p>Finally we wish to update the WaveCount, so that players can get a feeling for how far through the game they are, and have something to aim for (ie. a previous highest level). </p>
<p>In gameHUd.com add the following function (and header):</p>
<pre class="brush:c++">
-(void) updateWaveCount {
      waveCount++;
      [self->waveCountLabel setString:[NSString stringWithFormat: @"Wave %i",waveCount]];
}
</pre>
<p>next go into TutorialScene and the update function, find the if statement which detects the end of the current wave and add a call to the updateWaveCount function. </p>
<pre class="brush:c++">
Wave *wave = [self getCurrentWave];
if ([m._targets count] ==0 &#038;&#038; wave.redCreeps <= 0 &#038;&#038; wave.greenCreeps <= 0) {
      [self getNextWave];
      [gameHUD updateWaveCount];
}
</pre>
<p>And there we have it!   We now have 3 dynamic labels, with corresponding logic, and also have prices for each tower. The actual prices, resource spawn rates and starting resources are all nominal, feel free to change these settings to get the balance of challenge and enjoyment that you wish. </p>
<p>Yours,<br />
Aiden Fry<br />
iPhone Game Tutorials Contributor</p>
<p>Aiden Fry is a recent graduate, working to get into the games industry. He is a games programmer with a special interest in audio programming. Please check out his website <a href="http://aidenfry.tk" target="_blank">aidenfry.tk</a> to see some of his work.</p>

<div class="jwsharethis">
Share this: 
<br />
<a href="mailto:?subject=How%20to%20Build%20a%20Tower%20Defense%20Game%20for%20the%20iPhone%20%26%238211%3B%20Part%207%20%26%238211%3B%20Money%20and%20Health&amp;body=http%3A%2F%2Fwww.iphonegametutorials.com%2F2012%2F01%2F24%2Fhow-to-build-a-tower-defense-game-for-the-iphone-part-7-money-and-health%2F">
<img src="http://www.iphonegametutorials.com/wp-content/plugins/jw-share-this/email.png" alt="Share this page via Email" />
</a>
<a target="_blank" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.iphonegametutorials.com%2F2012%2F01%2F24%2Fhow-to-build-a-tower-defense-game-for-the-iphone-part-7-money-and-health%2F&amp;title=How+to+Build+a+Tower+Defense+Game+for+the+iPhone+%26%238211%3B+Part+7+%26%238211%3B+Money+and+Health">
<img src="http://www.iphonegametutorials.com/wp-content/plugins/jw-share-this/su.png" alt="Share this page via Stumble Upon" />
</a>
<a target="_blank" href="http://digg.com/submit?url=http%3A%2F%2Fwww.iphonegametutorials.com%2F2012%2F01%2F24%2Fhow-to-build-a-tower-defense-game-for-the-iphone-part-7-money-and-health%2F&amp;title=How+to+Build+a+Tower+Defense+Game+for+the+iPhone+%26%238211%3B+Part+7+%26%238211%3B+Money+and+Health">
<img src="http://www.iphonegametutorials.com/wp-content/plugins/jw-share-this/digg.png" alt="Share this page via Digg this" />
</a>
<a target="_blank" href="http://www.facebook.com/sharer.php?u=http%3A%2F%2Fwww.iphonegametutorials.com%2F2012%2F01%2F24%2Fhow-to-build-a-tower-defense-game-for-the-iphone-part-7-money-and-health%2F&amp;t=How+to+Build+a+Tower+Defense+Game+for+the+iPhone+%26%238211%3B+Part+7+%26%238211%3B+Money+and+Health">
<img src="http://www.iphonegametutorials.com/wp-content/plugins/jw-share-this/fb.png" alt="Share this page via Facebook" />
</a>
<a target="_blank" href="http://twitter.com/intent/tweet?text=I+like+http%3A%2F%2Fwww.iphonegametutorials.com%2F2012%2F01%2F24%2Fhow-to-build-a-tower-defense-game-for-the-iphone-part-7-money-and-health%2F&amp;title=How+to+Build+a+Tower+Defense+Game+for+the+iPhone+%26%238211%3B+Part+7+%26%238211%3B+Money+and+Health">
<img src="http://www.iphonegametutorials.com/wp-content/plugins/jw-share-this/twitter.png" alt="Share this page via Twitter" />
</a>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.iphonegametutorials.com/2012/01/24/how-to-build-a-tower-defense-game-for-the-iphone-part-7-money-and-health/feed/</wfw:commentRss>
		<slash:comments>28</slash:comments>
		</item>
		<item>
		<title>How To Build a Tower Defense Game for the iPhone – Part 6 – Tower Powers</title>
		<link>http://www.iphonegametutorials.com/2012/01/18/cocos2d-game-tutorial-%e2%80%93-how-to-build-a-tower-defense-game-for-the-iphone-part-6-tower-powers/</link>
		<comments>http://www.iphonegametutorials.com/2012/01/18/cocos2d-game-tutorial-%e2%80%93-how-to-build-a-tower-defense-game-for-the-iphone-part-6-tower-powers/#comments</comments>
		<pubDate>Wed, 18 Jan 2012 16:32:29 +0000</pubDate>
		<dc:creator>Aiden Fry</dc:creator>
				<category><![CDATA[Advanced]]></category>
		<category><![CDATA[Cocos2d]]></category>
		<category><![CDATA[Tower Defense]]></category>
		<category><![CDATA[cocos2d]]></category>
		<category><![CDATA[Download]]></category>
		<category><![CDATA[freeze towers]]></category>
		<category><![CDATA[ice projectiles]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[source code]]></category>
		<category><![CDATA[tower defense]]></category>
		<category><![CDATA[tower defense game]]></category>
		<category><![CDATA[tower powers]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://www.iphonegametutorials.com/?p=661</guid>
		<description><![CDATA[Welcome back to the Tower Defense Tutorial Series! Once again I am assuming that you have read the previous 5 parts of this tutorial and are happy with the content covered in them. In this Tutorial, we will be incorporating a new tower type into our game, this will give you the knowledge to then [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.iphonegametutorials.com/wp-content/uploads/2012/01/Screen-shot-2012-01-18-at-12.23.31-AM.png"><img src="http://www.iphonegametutorials.com/wp-content/uploads/2012/01/Screen-shot-2012-01-18-at-12.23.31-AM-300x156.png" alt="" title="Screen shot 2012-01-18 at 12.23.31 AM" width="300" height="156" class="alignleft size-medium wp-image-678" /></a>Welcome back to the Tower Defense Tutorial Series! Once again I am assuming that you have read the previous 5 parts of this tutorial and are happy with the content covered in them.</p>
<p>In this Tutorial, we will be incorporating a new tower type into our game, this will give you the knowledge to then continue on and make/implement your own towers types. The tower type which we will be incorporating is a freeze tower, this tower will shoot Ice projectiles at a creep which will freeze it in place for a period of time, before the creep then continues on its journey.</p>
<p>Source code after the break!<br />
<span id="more-661"></span></p>
<p>The first thing to do is to download the new Turret and Projectile images that I created in about 2 minutes. They can be found here: <a href="http://www.iphonegametutorials.com/wp-content/uploads/2012/01/FreezeTurret.png">Freeze Turret</a> and <a href="http://www.iphonegametutorials.com/wp-content/uploads/2012/01/IceProjectile.png">Ice Projectile</a>.  Alternatively you can use your own images (however i recommend re-naming them in the same way to avoid confusion later). Then add them to your resources folder in Xcode.  Alternatively if you want to just see everything in action, here is the source code: <a href="http://www.iphonegametutorials.com/wp-content/uploads/2012/01/TowerDefensePart6.zip">Tower Defense Part 6</a>.</p>
<p>Now we have our images in our project, we want to add our new turret image to our HUD so that the player can select and place it within the level. Open GameHUD.m and look at the init section.</p>
<pre class="brush:c++">
NSArray *images = [NSArray arrayWithObjects:@"MachineGunTurret.png", @"FreezeTurret.png", @"MachineGunTurret.png", @"MachineGunTurret.png", nil];
for(int i = 0; i < images.count; ++i) {
     NSString *image = [images objectAtIndex:i];
     CCSprite *sprite = [CCSprite spriteWithFile:image];
     float offsetFraction = ((float)(i+1))/(images.count+1);
     sprite.position = ccp(winSize.width*offsetFraction, 35);
     sprite.tag = i+1;//individual tag for each Turret.
     [self addChild:sprite];
     [movableSprites addObject:sprite];
</pre>
<p>Within the "NSArray *images" we have changed the second "MachineGunTurret.png" to "FreezeTurret.png". This will load the freeze turret image as the second from the left image. Then in the "for loop" we added an individual tag to each tower type, "sprite.tag = i+1;" I chose to +1 so that the first Turret type(MachineGunTurret) starts at 1 rather than 0. And the New FreezeTurret will have a tag of 2. For now, turret types 3 + 4 are still machine gun turrets, but once you have completed this tutorial, feel free to add your own turrets types in here.</p>
<p>While we are in GameHUD.m go down to ccTouchesBegan and add the following piece of code directly above the line "[self addChild:newSprite];"</p>
<pre class="brush:c++">
selSprite.tag = sprite.tag;
</pre>
<p>then go down to ccTouchedEnded and adjust the if statement:</p>
<pre class="brush:c++">
if (!CGRectContainsPoint(backgroundRect, touchLocation))
</pre>
<p>to say:</p>
<pre class="brush:c++">
if (!CGRectContainsPoint(backgroundRect, touchLocation)) {
     CGPoint touchLocationInGameLayer = [m._gameLayer convertTouchToNodeSpace:touch];
     [m._gameLayer addTower: touchLocationInGameLayer: selSprite.tag];
}
</pre>
<p>What do these changes do? In effect they take the tag of the currently selected turret type, and pass it to the addTower function in TutorialScene.m, when the player lets go of the tower placing it within the level. To get rid of the pesky error messages which are now occurring we need to adjust the addTower function.<br />
Go into TutorialScene.h replace the addTower function definition with the following:</p>
<pre class="brush:c++">
- (void)addTower: (CGPoint)pos: (int)towerTag;
</pre>
<p>then in TutorialScene.m replace the addTower function header (not the contents of the function) with the following:</p>
<pre class="brush:c++">
-(void)addTower: (CGPoint)pos: (int)towerTag{
     //Keep the same function content!
}
</pre>
<p>At this moment in time, if we run the game, we will see the FreezeTurret in the HUD and be able to select and move it, however when we place it on the map, it will transform into a MachineGunTurret.This is partly because we have not created the FreezeTower class, we shall do this now.  Open Tower.m and copy and paste the following class at the very end of the file (after @end).</p>
<pre class="brush:c++">
@implementation FreezeTower
+ (id)tower {
     FreezeTower *tower = nil;
     if ((tower = [[[super alloc] initWithFile:@"FreezeTurret.png"] autorelease])) {
          tower.range = 200;
          tower.target = nil;
          [tower schedule:@selector(towerLogic:) interval:2];
     }

     return tower;
}

-(id) init
{
     if ((self=[super init]) ) {
          //[[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES];
     }

     return self;
}

-(void)setClosestTarget:(Creep *)closestTarget {
     self.target = closestTarget;
}

-(void)towerLogic:(ccTime)dt {
     self.target = [self getClosestTarget];

     if (self.target != nil) {
          //rotate the tower to face the nearest creep

          CGPoint shootVector = ccpSub(self.target.position, self.position);
          CGFloat shootAngle = ccpToAngle(shootVector);
          CGFloat cocosAngle = CC_RADIANS_TO_DEGREES(-1 * shootAngle);

          float rotateSpeed = 0.5 / M_PI; // 1/2 second to roate 180 degrees
          float rotateDuration = fabs(shootAngle * rotateSpeed);

          [self runAction:[CCSequence actions: [CCRotateTo actionWithDuration:rotateDuration angle:cocosAngle], [CCCallFunc actionWithTarget:self selector:@selector(finishFiring)], nil]];
     }
}

-(void)creepMoveFinished:(id)sender {
     DataModel * m = [DataModel getModel];

     CCSprite *sprite = (CCSprite *)sender; [self.parent removeChild:sprite cleanup:YES];

     [m._projectiles removeObject:sprite];
}

- (void)finishFiring {
     DataModel *m = [DataModel getModel];
     self.nextProjectile = [Projectile projectile];
     self.nextProjectile.position = self.position;
     [self.parent addChild:self.nextProjectile z:1];
     [m._projectiles addObject:self.nextProjectile];

     ccTime delta = 0.5;
     CGPoint shootVector = ccpSub(self.target.position, self.position);
     CGPoint normalizedShootVector = ccpNormalize(shootVector);
     CGPoint overshotVector = ccpMult(normalizedShootVector, 320);
     CGPoint offscreenPoint = ccpAdd(self.position, overshotVector);

     [self.nextProjectile runAction:[CCSequence actions: [CCMoveTo actionWithDuration:delta position:offscreenPoint], [CCCallFuncN actionWithTarget:self selector:@selector(creepMoveFinished:)], nil]];
     self.nextProjectile.tag = 2;!!
     self.nextProjectile = nil;
}
@end
</pre>
<p>then in Tower.H: copy and paste the following class definitions at the very end of the file (after @end)</p>
<pre class="brush:c++">
@interface FreezeTower : Tower {

}

+ (id)tower;
- (void)setClosestTarget:(Creep *)closestTarget;
- (void)towerLogic:(ccTime)dt;
- (void)creepMoveFinished:(id)sender;
- (void)finishFiring;
@end
</pre>
<p>So what have we done here? Well if you look through the code you will see that we have done very little apart from copy the MachineGunTurret class and change a few parameters. Such as: the image, the fire rate of the turret (towerLogic schedule), the speed of the projectile (just made it a bit faster).  So now we have our FreezeTurret class, we should go back into addTower and allow it to create a FreezeTurret if a player selects a freeze turret.  Now open TutorialScene.m, and go to the addTower function. Under the check to see if the tile is build able add in the following:</p>
<pre class="brush:c++">
NSLog(@"Buildable: %@", type);
if([type isEqualToString: @"1"]) {
     printf("tower tag %i", towerTag);

     switch (towerTag) {
          case 1:
               target = [MachineGunTower tower];
          break;
          case 2:
               target = [FreezeTower tower];
          break;
          case 3:
               target = [MachineGunTower tower];
          break;
          case 4:
               target = [MachineGunTower tower];
          break;
          default:
          break;
     }
</pre>
<p>Now our towerTag, passed from GameHUD, comes in handy as we check to see which tower the player has selected. When the player lets go we add the same tower type to the level.  So now we should be able to select and add two different classes of Tower to our game world.</p>
<p>Run, Check, Debug.</p>
<p>Ok, so you might have noticed, at the moment the FreezeTurret behaves more like a slow MachineGunTurret than a FreezeTurret. In this next section we shall improve on this by adding the freeze logic to the update function, and then allowing the creeps to resume its path. The first thing that we should do is to go into Tower.M and make sure that the projectiles coming from MachineGunTurret have a tag of 1. Whilst the projectiles coming from FreezeTurret have a tag of 2. Next, open TutorialScene.m and go down to our Update function, and find the section where we check for collisions between projectiles and creeps and replace the entire if statement with the following.</p>
<pre class="brush:c++">
if (CGRectIntersectsRect(projectileRect, targetRect)) {
     [projectilesToDelete addObject:projectile];
     Creep *creep = (Creep *)target;

     if (projectile.tag ==1) { //MachineGun Projectile
          creep.hp--;
          if (creep.hp <= 0) {
               [targetsToDelete addObject:target];
          }
          break;
     }
     else if (projectile.tag ==2) { //Freeze projectile
     id actionFreeze = [CCMoveTo actionWithDuration:1 position:creep.position];
     id actionMoveResume = [CCCallFuncN actionWithTarget:self selector:@selector(ResumePath:)];
     [creep stopAllActions];
     [creep runAction:[CCSequence actions:actionFreeze, actionMoveResume, nil]];
     break;
     }
     break;
}
</pre>
<p>When a collision between a projectile and a creep is detected, we then check to see what the projectile tag is. If the projectile.tag == 1 then we know this projectile come from a MachineGunTurret and we perform the same actions as we have done in the previous tutorials. However if the projectile.tag == 2 then we know this is a freeze projectile, in which case we run a series of actions. First we Freeze the creep for 1 second at its current location. Then we call a new function ResumePath:, in which we will allow the creep to continue along its path.</p>
<p>in tutorialscene.m add in the following function</p>
<pre class="brush:c++">
-(void)ResumePath:(id)sender {
     Creep *creep = (Creep *)sender;
     WayPoint * cWaypoint = [creep getCurrentWaypoint];//destination
     WayPoint * lWaypoint = [creep getLastWaypoint];//startpoint
     float waypointDist = fabsf(cWaypoint.position.x -lWaypoint.position.x);
     float playerDist = fabsf(creep.position.x - cWaypoint.position.x);
     float distFraction = playerDist / waypointDist;
     float moveDuration = creep.moveDuration * (distFraction); //Time it takes to go from one way point to another * the fraction of how far is left to go (meaning it will move at the correct speed)

     id actionMove = [CCMoveTo actionWithDuration:moveDuration position:cWaypoint.position];
     id actionMoveDone = [CCCallFuncN actionWithTarget:self selector:@selector(FollowPath:)];
     [creep stopAllActions];
     [creep runAction:[CCSequence actions:actionMove, actionMoveDone, nil]];
}
</pre>
<p>then in creep.m add in the following function</p>
<pre class="brush:c++">
- (WayPoint *)getLastWaypoint{
     DataModel *m = [DataModel getModel];
     //int lastWaypoint = m._waypoints.count;
     self.lastWaypoint = self.curWaypoint -1;
     WayPoint *waypoint = (WayPoint *) [m._waypoints objectAtIndex:self.lastWaypoint];
     return waypoint;
}
</pre>
<p>[Side Note: REMEMBER TO ADD IN THE HEADERS FOR THESE FUNCTIONS.]</p>
<p>What do we do in these functions? Well in essence we find the distance between the previous waypoint and the current waypoint. Then we find the distance between the creep and the current waypoint. We then represent the distance between the creep and the current waypoint as a fraction of the distance between the last waypoint and the current waypoint. Then we use this fraction to affect the creep.moveDuration so that when the creep continues towards the current waypoint, it moves at a speed relative to its fellow creeps. After it hits the current waypoint it will then continue along its path normally.  One thing that I would like to do here is to correct a slight error which occurs within the creep.m code. Replace the getNextWaypoint function with the following:</p>
<p>[Update: found a small issue in the getNextWaypoint function that would cause the health bar to act weird - It's been fixed now in the below code]</p>
<pre class="brush:c++">
- (WayPoint *)getNextWaypoint{
DataModel *m = [DataModel getModel];
self.curWaypoint++;

if (self.curWaypoint >= m._waypoints.count){
        self.curWaypoint--;
        gameHUD = [GameHUD sharedHUD];
        if (gameHUD.baseHpPercentage > 0) {
            [gameHUD updateBaseHp:-10];
        }

        Creep *target = (Creep *) self;
        NSMutableArray *endtargetsToDelete = [[NSMutableArray alloc] init];
        [endtargetsToDelete addObject:target];

        for (CCSprite *target in endtargetsToDelete) {
            [m._targets removeObject:target];
            [self.parent removeChild:target cleanup:YES];
        }
        return NULL;

    }

WayPoint *waypoint = (WayPoint *) [m._waypoints objectAtIndex:self.curWaypoint];
return waypoint;

}
</pre>
<p>If you have noticed an intermittent crash, it is because when the creeps gets to the last waypoint this function was not working correctly. However this update will recognize when a creep is at the last waypoint and delete the creep. So, run this and we should see that the FreezeTowers, freeze the creeps, and then the creeps (after one second) will continue along their path at a normal speed.</p>
<p>One final thing we can implement is to add in an IceProjectile that the FreezeTower fires, rather than the usual machine gun projectile. Once again this is fairly simple, open Projectile.m and add the following class at the end of the file (after @end):</p>
<pre class="brush:c++">
@implementation IceProjectile
+ (id)projectile {
     IceProjectile *projectile = nil;
     if ((projectile = [[[super alloc] initWithFile:@"IceProjectile.png"] autorelease])) {

     }
     return projectile;
}

- (void) dealloc
{
     [super dealloc];
}

@end
</pre>
<p>then in Projectile.h add the following at the end of the file:</p>
<pre class="brush:c++">
@interface IceProjectile : CCSprite {
}

+ (id)projectile;
@end
</pre>
<p>Simply this creates another class of projectile, the IceProjectile. Now go into Tower.h and go down to the FreezeTower class, and find the function finishedFiring. Adjust the call to [Projectile projectile]; to say the following:</p>
<pre class="brush:c++">
self.nextProjectile = [IceProjectile projectile];
</pre>
<p>And there we have it! FreezeTowers, IceProjectiles, and FreezeCreep functionality.  As always, comments / suggestions / found errors? All very welcome! Thanks for Reading!</p>
<p>Yours,<br />
Aiden Fry<br />
iPhone Game Tutorials Contributor</p>
<p>Aiden Fry is a recent graduate, working to get into the games industry. He is a games programmer with a special interest in audio programming. Please check out his website <a href="http://aidenfry.tk" target="_blank">aidenfry.tk</a> to see some of his work.</p>

<div class="jwsharethis">
Share this: 
<br />
<a href="mailto:?subject=How%20To%20Build%20a%20Tower%20Defense%20Game%20for%20the%20iPhone%20%E2%80%93%20Part%206%20%E2%80%93%20Tower%20Powers&amp;body=http%3A%2F%2Fwww.iphonegametutorials.com%2F2012%2F01%2F18%2Fcocos2d-game-tutorial-%25e2%2580%2593-how-to-build-a-tower-defense-game-for-the-iphone-part-6-tower-powers%2F">
<img src="http://www.iphonegametutorials.com/wp-content/plugins/jw-share-this/email.png" alt="Share this page via Email" />
</a>
<a target="_blank" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.iphonegametutorials.com%2F2012%2F01%2F18%2Fcocos2d-game-tutorial-%25e2%2580%2593-how-to-build-a-tower-defense-game-for-the-iphone-part-6-tower-powers%2F&amp;title=How+To+Build+a+Tower+Defense+Game+for+the+iPhone+%E2%80%93+Part+6+%E2%80%93+Tower+Powers">
<img src="http://www.iphonegametutorials.com/wp-content/plugins/jw-share-this/su.png" alt="Share this page via Stumble Upon" />
</a>
<a target="_blank" href="http://digg.com/submit?url=http%3A%2F%2Fwww.iphonegametutorials.com%2F2012%2F01%2F18%2Fcocos2d-game-tutorial-%25e2%2580%2593-how-to-build-a-tower-defense-game-for-the-iphone-part-6-tower-powers%2F&amp;title=How+To+Build+a+Tower+Defense+Game+for+the+iPhone+%E2%80%93+Part+6+%E2%80%93+Tower+Powers">
<img src="http://www.iphonegametutorials.com/wp-content/plugins/jw-share-this/digg.png" alt="Share this page via Digg this" />
</a>
<a target="_blank" href="http://www.facebook.com/sharer.php?u=http%3A%2F%2Fwww.iphonegametutorials.com%2F2012%2F01%2F18%2Fcocos2d-game-tutorial-%25e2%2580%2593-how-to-build-a-tower-defense-game-for-the-iphone-part-6-tower-powers%2F&amp;t=How+To+Build+a+Tower+Defense+Game+for+the+iPhone+%E2%80%93+Part+6+%E2%80%93+Tower+Powers">
<img src="http://www.iphonegametutorials.com/wp-content/plugins/jw-share-this/fb.png" alt="Share this page via Facebook" />
</a>
<a target="_blank" href="http://twitter.com/intent/tweet?text=I+like+http%3A%2F%2Fwww.iphonegametutorials.com%2F2012%2F01%2F18%2Fcocos2d-game-tutorial-%25e2%2580%2593-how-to-build-a-tower-defense-game-for-the-iphone-part-6-tower-powers%2F&amp;title=How+To+Build+a+Tower+Defense+Game+for+the+iPhone+%E2%80%93+Part+6+%E2%80%93+Tower+Powers">
<img src="http://www.iphonegametutorials.com/wp-content/plugins/jw-share-this/twitter.png" alt="Share this page via Twitter" />
</a>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.iphonegametutorials.com/2012/01/18/cocos2d-game-tutorial-%e2%80%93-how-to-build-a-tower-defense-game-for-the-iphone-part-6-tower-powers/feed/</wfw:commentRss>
		<slash:comments>21</slash:comments>
		</item>
		<item>
		<title>How To Build a Tower Defense Game for the iPhone – Part 5b – More Wave Control</title>
		<link>http://www.iphonegametutorials.com/2012/01/12/cocos2d-game-tutorial-%e2%80%93-how-to-build-a-tower-defense-game-for-the-iphone-part-5b-more-wave-control/</link>
		<comments>http://www.iphonegametutorials.com/2012/01/12/cocos2d-game-tutorial-%e2%80%93-how-to-build-a-tower-defense-game-for-the-iphone-part-5b-more-wave-control/#comments</comments>
		<pubDate>Thu, 12 Jan 2012 18:13:18 +0000</pubDate>
		<dc:creator>Aiden Fry</dc:creator>
				<category><![CDATA[Advanced]]></category>
		<category><![CDATA[Cocos2d]]></category>
		<category><![CDATA[Tower Defense]]></category>
		<category><![CDATA[Download]]></category>
		<category><![CDATA[game]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[source]]></category>
		<category><![CDATA[source code]]></category>
		<category><![CDATA[tower defense]]></category>

		<guid isPermaLink="false">http://www.iphonegametutorials.com/?p=585</guid>
		<description><![CDATA[And we are back! Well, wasn&#8217;t that fun, we now have a multiple wave game, which we can program to increase in difficulty as we go along. However, there is still one thing nagging at me&#8230;.. We still have no real control over how many creeps of each type are spawned in a wave, what [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.iphonegametutorials.com/wp-content/uploads/2012/01/SS3.png"><img src="http://www.iphonegametutorials.com/wp-content/uploads/2012/01/SS3-300x156.png" alt="" title="SS3" width="300" height="156" class="alignleft size-medium wp-image-646" /></a>And we are back! Well, wasn&#8217;t that fun, we now have a multiple wave game, which we can program to increase in difficulty as we go along. However, there is still one thing nagging at me&#8230;..  We still have no real control over how many creeps of each type are spawned in a wave, what if we wanted one wave to be completely made up of Red creeps, or Green Creeps. There are a few ways to do this, but I will explain the way that I did it.</p>
<p>Before we get into it, you&#8217;ll find things much easier to follow if you&#8217;ve already looked at Part5a of this tutorial series &#8211; So go there and come back&#8230; don&#8217;t worry we&#8217;ll wait.</p>
<p>Source code after the break&#8230;<br />
<span id="more-585"></span></p>
<p>Here is the source code: <a href="http://www.iphonegametutorials.com/wp-content/uploads/2012/01/TowerDefensePart5b.zip">Tower Defense Part 5b</a>.  Once again, we&#8217;re using the <a href="http://www.cocos2d-iphone.org/download">Cocos2d framework which you can download here</a>!</p>
<p>The first thing I did is to change the make up of the wave class. open wave.m and adjust the initWithCreep function to the following.</p>
<pre class="brush:c++">- (id) initWithCreep:(Creep *)creep SpawnRate:(float)spawnrate RedCreeps:(int)redcreeps GreenCreeps: (int)greencreeps
{
     NSAssert(creep!=nil, @"Invalid creep for wave.");
     if( (self = [self init]) )
     {
          _creepType = creep;
          _spawnRate = spawnrate;
          _redCreeps = redcreeps;
          _greenCreeps = greencreeps;
     }
     return self;
}</pre>
<p>Also add your new variables as such (and remove totalCreeps variables):</p>
<pre class="brush:c++">@synthesize redCreeps = _redCreeps;
@synthesize greenCreeps = _greenCreeps;</pre>
<p>Whilst in wave.H replace the entire file with the following:</p>
<pre class="brush:c++">#import "cocos2d.h"
#import "Creep.h"

@interface Wave : CCNode {
    float _spawnRate;
    int _redCreeps;
    int _greenCreeps;
    Creep * _creepType;
}

@property (nonatomic) float spawnRate;
@property (nonatomic) int redCreeps;
@property (nonatomic) int greenCreeps;
@property (nonatomic, retain) Creep *creepType;
- (id)initWithCreep:(Creep *)creep SpawnRate:(float)spawnrate RedCreeps:
(int)redcreeps GreenCreeps:(int)greencreeps;
@end</pre>
<p>Hold up: All that we have done here is to change the make-up of the initWithCreep function (used in addWaves) to allow us to set the amount of red and green creeps separately, instead of just a totalCreeps value. Now go back into the main file (yep we have some errors, don’t worry!) and go to the function addWaves.  Here we need to change our definitions to now include our RedCreeps and GreenCreeps variables (removing the TotalCreeps variable) until we have something which looks like this.</p>
<pre class="brush:c++">      wave = [[Wave alloc] initWithCreep:[FastRedCreep creep] SpawnRate: 0.7 RedCreeps:5 GreenCreeps:15];</pre>
<p>Still we have some errors, no problem, this is because we were checking the TotalCreeps in a few places, however with this variable now nonexistent we need to change these checks.<br />
in addTarget change:</p>
<pre class="brush:c++">if (wave.totalCreeps &lt; 0) {
     return;
}</pre>
<p>to</p>
<pre class="brush:c++">if (wave.redCreeps &lt;= 0 &amp;&amp; wave.greenCreeps &lt;= 0 ) {
     return;
}</pre>
<p>Hold up: Simply this means that we won’t spawn any more creeps than are in the wave, and now we have split the creeps into green and red, we need to check that both are at 0.  Next up you will see something like this</p>
<pre class="brush:c++">wave.totalCreeps--;</pre>
<p>remove this piece of code. This was lowering the count of creeps left to spawn in this wave, however we will now do the same thing in a different way. Below this line you will see the next section of code:</p>
<pre class="brush:c++">Creep *target = nil;
if ((arc4random() % 2) == 0) {
     target = [FastRedCreep creep];
} else {
     target = [StrongGreenCreep creep];
}</pre>
<p>In this section we set the creep type to spawn at random, evenly between Red and Green creeps. Replace this code with the following.</p>
<pre class="brush:c++">Creep *target = nil;
if ((arc4random() % 2) == 0) {
      if (wave.redCreeps &gt; 0) {
            target = [FastRedCreep creep];
            wave.redCreeps--;
      }
      else if (wave.greenCreeps &gt;0){
            target = [StrongGreenCreep creep];
            wave.greenCreeps--;
            // NSLog(@"no more red");
      }
}
else {
      if (wave.greenCreeps &gt;0) {
            target = [StrongGreenCreep creep];
            wave.greenCreeps--;
      }
      else if (wave.redCreeps &gt;0){
            target = [FastRedCreep creep];
            wave.redCreeps--;
            //NSLog(@"no more green");
      }
}</pre>
<p>Hold up: In the new code above we are once again choosing a creep type (red/green) at random, however we then check to see if there are any creeps of that type left to spawn in this wave. This is a bit wordy so I&#8217;ll give a little example.</p>
<p>If the random generator chooses a Red Creep, and there is at least 1 Red Creep left to spawn in this wave, then a Red Creep is spawned and we decrease the number of Reds left to spawn in this wave. If there are not any Red Creeps left to spawn, then we Spawn a Green Creep and decrease the number of Green Creeps left to spawn in this wave. There I hope you understood that, should be fairly simple even if I can’t really vocalize it concisely.<br />
Oh yes, and finally one last change. Go to the update section, where we earlier implemented a check for the end of the wave and replace the if statement with the following.</p>
<pre class="brush:c++">Wave *wave = [self getCurrentWave];
//int alivecount = [m._targets count];
if ([m._targets count] ==0 &amp;&amp; wave.redCreeps &lt;= 0 &amp;&amp; wave.greenCreeps &lt;= 0) {
      printf("Get next wave\n");
      // NSLog(@"Get next wave\n");//use for debugging
      [self getNextWave];
}</pre>
<p>Hold up: Should understand this by now as it is the same general update we have been doing from wave.totalCreeps (expired) to wave.redCreeps and Wave.greenCreeps.</p>
<p>Run, Test, Enjoy!</p>
<p>Remember, here is the source code for everything we have covered within this tutorial!</p>
<p><a href="http://www.iphonegametutorials.com/wp-content/uploads/2012/01/TowerDefensePart5b.zip">Tower Defense Part 5b Download</a>.</p>
<p>Thanks for Reading, Hope this helps you all. Comment for help/explanations/pointing out any “doh” moments from me! Also Comment for suggestions for where you want this series to go next.</p>
<p>Yours,<br />
Aiden Fry<br />
iPhone Game Tutorials Contributor</p>
<p>Aiden Fry is a recent graduate, working to get into the games industry. He is a games programmer with a special interest in audio programming. Please check out his website <a href="http://aidenfry.tk">aidenfry.tk</a> to see some of his work.</p>

<div class="jwsharethis">
Share this: 
<br />
<a href="mailto:?subject=How%20To%20Build%20a%20Tower%20Defense%20Game%20for%20the%20iPhone%20%E2%80%93%20Part%205b%20%E2%80%93%20More%20Wave%20Control&amp;body=http%3A%2F%2Fwww.iphonegametutorials.com%2F2012%2F01%2F12%2Fcocos2d-game-tutorial-%25e2%2580%2593-how-to-build-a-tower-defense-game-for-the-iphone-part-5b-more-wave-control%2F">
<img src="http://www.iphonegametutorials.com/wp-content/plugins/jw-share-this/email.png" alt="Share this page via Email" />
</a>
<a target="_blank" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.iphonegametutorials.com%2F2012%2F01%2F12%2Fcocos2d-game-tutorial-%25e2%2580%2593-how-to-build-a-tower-defense-game-for-the-iphone-part-5b-more-wave-control%2F&amp;title=How+To+Build+a+Tower+Defense+Game+for+the+iPhone+%E2%80%93+Part+5b+%E2%80%93+More+Wave+Control">
<img src="http://www.iphonegametutorials.com/wp-content/plugins/jw-share-this/su.png" alt="Share this page via Stumble Upon" />
</a>
<a target="_blank" href="http://digg.com/submit?url=http%3A%2F%2Fwww.iphonegametutorials.com%2F2012%2F01%2F12%2Fcocos2d-game-tutorial-%25e2%2580%2593-how-to-build-a-tower-defense-game-for-the-iphone-part-5b-more-wave-control%2F&amp;title=How+To+Build+a+Tower+Defense+Game+for+the+iPhone+%E2%80%93+Part+5b+%E2%80%93+More+Wave+Control">
<img src="http://www.iphonegametutorials.com/wp-content/plugins/jw-share-this/digg.png" alt="Share this page via Digg this" />
</a>
<a target="_blank" href="http://www.facebook.com/sharer.php?u=http%3A%2F%2Fwww.iphonegametutorials.com%2F2012%2F01%2F12%2Fcocos2d-game-tutorial-%25e2%2580%2593-how-to-build-a-tower-defense-game-for-the-iphone-part-5b-more-wave-control%2F&amp;t=How+To+Build+a+Tower+Defense+Game+for+the+iPhone+%E2%80%93+Part+5b+%E2%80%93+More+Wave+Control">
<img src="http://www.iphonegametutorials.com/wp-content/plugins/jw-share-this/fb.png" alt="Share this page via Facebook" />
</a>
<a target="_blank" href="http://twitter.com/intent/tweet?text=I+like+http%3A%2F%2Fwww.iphonegametutorials.com%2F2012%2F01%2F12%2Fcocos2d-game-tutorial-%25e2%2580%2593-how-to-build-a-tower-defense-game-for-the-iphone-part-5b-more-wave-control%2F&amp;title=How+To+Build+a+Tower+Defense+Game+for+the+iPhone+%E2%80%93+Part+5b+%E2%80%93+More+Wave+Control">
<img src="http://www.iphonegametutorials.com/wp-content/plugins/jw-share-this/twitter.png" alt="Share this page via Twitter" />
</a>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.iphonegametutorials.com/2012/01/12/cocos2d-game-tutorial-%e2%80%93-how-to-build-a-tower-defense-game-for-the-iphone-part-5b-more-wave-control/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>How To Build a Tower Defense Game for the iPhone – Part 5a – Multiple Waves</title>
		<link>http://www.iphonegametutorials.com/2012/01/11/cocos2d-game-tutorial-%e2%80%93-how-to-build-a-tower-defense-game-for-the-iphone-part-5a-multiple-waves/</link>
		<comments>http://www.iphonegametutorials.com/2012/01/11/cocos2d-game-tutorial-%e2%80%93-how-to-build-a-tower-defense-game-for-the-iphone-part-5a-multiple-waves/#comments</comments>
		<pubDate>Wed, 11 Jan 2012 18:02:55 +0000</pubDate>
		<dc:creator>Aiden Fry</dc:creator>
				<category><![CDATA[Advanced]]></category>
		<category><![CDATA[Cocos2d]]></category>
		<category><![CDATA[Tower Defense]]></category>
		<category><![CDATA[cocos2d]]></category>
		<category><![CDATA[Download]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[source code]]></category>
		<category><![CDATA[tower defense]]></category>
		<category><![CDATA[tower defense game]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[Tutorials]]></category>

		<guid isPermaLink="false">http://www.iphonegametutorials.com/?p=552</guid>
		<description><![CDATA[[Editor's Note: One of our readers spoke up and decided to help us finish off this series of tutorials. Many thanks to Aiden Fry for stepping up to the plate!] Welcome to the latest edition of the Tower Defense Tutorial. This is just the start of the long awaited renewal of the Tower Defense Tutorials. [...]]]></description>
			<content:encoded><![CDATA[<p>[<strong>Editor's Note</strong>: <em>One of our readers spoke up and decided to help us finish off this series of tutorials. Many thanks to <a href="http://www.aidenfry.tk">Aiden Fry</a> for stepping up to the plate!</em>]</p>
<p><a href="http://www.iphonegametutorials.com/wp-content/uploads/2012/01/SS1.png"><img class="alignleft size-medium wp-image-639" title="SS1" src="http://www.iphonegametutorials.com/wp-content/uploads/2012/01/SS1-300x158.png" alt="" width="300" height="158" /></a>Welcome to the latest edition of the Tower Defense Tutorial. This is just the start of the long awaited renewal of the Tower Defense Tutorials. I (like many of you I am sure), have been following this particular tutorial series with interest, and was slightly downcast when I realized that part 4 was the last to be released. So hear me now, I vow to take up the challenge and by the end of these tutorials we will have a fully working game!</p>
<p>Yours, Aiden.</p>
<p>[<strong>Editor's Note:</strong> <em>We are also very happy that Aiden has taken up the challenge as well!</em>]</p>
<p>The Tower Defense Tutorial Part 5a &#8211; Multiple Waves!</p>
<p>A Quick Look Back:<br />
I will assume that all of you have been following the tutorial series found here &#8211; <a href="http://www.iphonegametutorials.com/2011/04/11/cocos2d-game-tutorial-how-to-build-a-tower-defense-game-for-the-iphone-part-1-creep-waves/">part 1</a>, <a href="http://www.iphonegametutorials.com/2011/04/15/cocos2d-game-tutorial-how-to-build-a-tower-defense-game-for-the-iphone-part-2-placing-towers/">part 2</a>, <a href="http://www.iphonegametutorials.com/2011/04/19/cocos2d-game-tutorial-%e2%80%93-how-to-build-a-tower-defense-game-for-the-iphone-%e2%80%93-part-3-%e2%80%93-rotation-and-realism/">part 3</a>, <a href="http://www.iphonegametutorials.com/2011/04/21/cocos2d-game-tutorial-how-to-build-a-tower-defense-game-for-the-iphone-part-4-starting-the-tower-attack/">part 4</a> &#8211; and are mostly OK with what has gone before, however it is good just to mention a few key things about what has already taken place.</p>
<ol>
<li>We have some creeps that go around a set path.</li>
<li>We can place towers around the path.</li>
<li>Towers fire at the nearest Creep.</li>
<li>Creeps have Hp, and when HP is 0 (due to tower projectiles) the creeps “die” and are removed from the game.</li>
<li>At the moment there is only one “Wave” of Creeps.</li>
</ol>
<p>Aims of this Tutorial:</p>
<ul>
<li>Creating Multiple waves of Creeps.</li>
<li>Defining how many Creeps of each type (red/green) per wave.</li>
</ul>
<p>Source code after the break&#8230;<br />
<span id="more-552"></span></p>
<p>Here is the source code: <a href="http://www.iphonegametutorials.com/wp-content/uploads/2012/01/TowerDefensePart5a.zip">Tower Defense Part 5a</a>.  Once again, we&#8217;re using the <a href="http://www.cocos2d-iphone.org/download">Cocos2d framework which you can download here</a>!</p>
<p>To create multiple waves, first we must define multiple waves, this is done in addWaves in TutorialScene.m, originally it should look like this.</p>
<pre class="brush:c++">-(void)addWaves {
     DataModel *m = [DataModel getModel];

     Wave *wave = nil;
     wave = [[Wave alloc] initWithCreep:[FastRedCreep creep] SpawnRate: 0.3 TotalCreeps:50];
     [m._waves addObject:wave];
     wave = nil;
     wave = [[Wave alloc] initWithCreep:[StrongGreenCreep creep] SpawnRate:1.0 TotalCreeps:5];
     [m._waves addObject:wave];
     wave = nil;!
}</pre>
<p>Hold up: The above means that there are two waves defined, the first wave has a total of 50 creeps, and spawns a knew one at 0.3 creeps per second. The initWithCreep[fastred] or [stronggreem] actually means nil to zilch at the moment (as we are defining which creep type to spawn at random in addTarget) therefore I will be “init-ing” with fast red creep from now on to avoid confusion.<br />
After we define our wave, we add it to an array for storage/call back later and initialize our wave variable to nil.  Adding our own waves: Yep you guessed it, to define our own waves all we need to do is to add more lines to the addWaves function, and just adjust the spawn rate and totalcreeps (if you so wish).  I chose to create 5 waves, that will increase in difficulty as we progress.</p>
<pre class="brush:c++">-(void)addWaves {
     DataModel *m = [DataModel getModel];

     Wave *wave = nil;
     wave = [[Wave alloc] initWithCreep:[FastRedCreep creep] SpawnRate: 1.0 TotalCreeps:10];
     [m._waves addObject:wave];
     wave = nil;
     wave = [[Wave alloc] initWithCreep:[FastRedCreep creep] SpawnRate: 0.7 TotalCreeps:20];
     [m._waves addObject:wave];
     wave = nil;!
     wave = [[Wave alloc] initWithCreep:[FastRedCreep creep] SpawnRate: 0.5 TotalCreeps:50];
     [m._waves addObject:wave];
     wave = nil;
     wave = [[Wave alloc] initWithCreep:[FastRedCreep creep] SpawnRate: 0.3 TotalCreeps:70];
     [m._waves addObject:wave];
     wave = nil;
     wave = [[Wave alloc] initWithCreep:[FastRedCreep creep] SpawnRate: 0.2 TotalCreeps:100];
     [m._waves addObject:wave];
     wave = nil;
}</pre>
<p>One thing to mention here is that if we wish to spawn our creeps as faster than one per second, we must change our scheduler call to gameLogic.  Go to Tutorial.m and find the init function. Here you will see a call to game logic such as:</p>
<pre class="brush:c++">
[self schedule:@selector(gameLogic:) interval:1.0];
</pre>
<p>The gameLogic function looks at the spawn rate and compares it with the time that has passed since the last spawn. Therefor if we wanted a spawn rate of 0.1 and the gameLogic is scheduled at 1.0 when running the game the actual spawn rate will be 1.0. Therefor we must make sure that the gameLogic interval is a division of all the spawn rates. </p>
<p>I have set the gamescheduler to:</p>
<pre class="brush:c++">
[self schedule:@selector(gameLogic:) interval:0.1];
</pre>
<p>As 0.1 is a divisible factor of all my spawn rates, and therefor the creeps will spawn at the rate that i set them.</p>
<p>Note: be aware that making the gameLogic interval smaller we are increasing the processing overhead.</p>
<p>Spawning our waves: The next thing to do is to spawn the next wave once the current wave has been defeated., This is fairly simple. In the update function (right at the end of the update) add in the following code.</p>
<pre class="brush:c++">Wave *wave = [self getCurrentWave];
if ([m._targets count] ==0 &amp;&amp; wave.totalCreeps &lt;= 0) {
     // NSLog(@"Get next wave\n");//use for debugging
     [self getNextWave];
}</pre>
<p>Hold up: Simply what this piece of code does is to: get the current wave from m._waves array where we saved our waves to in addWaves, then check to see if there are any creeps currently on screen, and check to see that all the creeps have been spawned from the current wave. If these checks are correct, its means that we are at the end of the current wave and its time to load the next wave. There is one last thing to do before we test out our new wave system. Within getNextWave we check to see if we are at the end of our waves. So you will need to adjust this check for the amount of waves that you have included. For me this is 5 waves, however remember that it will count from 0 (unless you specify other wise).</p>
<pre class="brush:c++">if (self.currentLevel &gt;= 5){
     //self.currentLevel = 0;
     NSLog(@"you have reached the end of the game!");
}</pre>
<p>There you have it, multiple programmable waves! Run, Test, Have Fun.</p>
<p>Part B will be released soon, I promise &#8211; The source code for up until this point can be <a href="http://www.iphonegametutorials.com/wp-content/uploads/2012/01/TowerDefensePart5a.zip">downloaded here</a>.</p>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">C:\Users\owner\Downloads</div>
<p>Yours,<br />
Aiden Fry<br />
iPhone Game Tutorials Contributor</p>
<p>Aiden Fry is a recent graduate, working to get into the games industry. He is a games programmer with a special interest in audio programming. Please check out his website <a href="http://aidenfry.tk">aidenfry.tk</a> to see some of his work.</p>

<div class="jwsharethis">
Share this: 
<br />
<a href="mailto:?subject=How%20To%20Build%20a%20Tower%20Defense%20Game%20for%20the%20iPhone%20%E2%80%93%20Part%205a%20%E2%80%93%20Multiple%20Waves&amp;body=http%3A%2F%2Fwww.iphonegametutorials.com%2F2012%2F01%2F11%2Fcocos2d-game-tutorial-%25e2%2580%2593-how-to-build-a-tower-defense-game-for-the-iphone-part-5a-multiple-waves%2F">
<img src="http://www.iphonegametutorials.com/wp-content/plugins/jw-share-this/email.png" alt="Share this page via Email" />
</a>
<a target="_blank" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.iphonegametutorials.com%2F2012%2F01%2F11%2Fcocos2d-game-tutorial-%25e2%2580%2593-how-to-build-a-tower-defense-game-for-the-iphone-part-5a-multiple-waves%2F&amp;title=How+To+Build+a+Tower+Defense+Game+for+the+iPhone+%E2%80%93+Part+5a+%E2%80%93+Multiple+Waves">
<img src="http://www.iphonegametutorials.com/wp-content/plugins/jw-share-this/su.png" alt="Share this page via Stumble Upon" />
</a>
<a target="_blank" href="http://digg.com/submit?url=http%3A%2F%2Fwww.iphonegametutorials.com%2F2012%2F01%2F11%2Fcocos2d-game-tutorial-%25e2%2580%2593-how-to-build-a-tower-defense-game-for-the-iphone-part-5a-multiple-waves%2F&amp;title=How+To+Build+a+Tower+Defense+Game+for+the+iPhone+%E2%80%93+Part+5a+%E2%80%93+Multiple+Waves">
<img src="http://www.iphonegametutorials.com/wp-content/plugins/jw-share-this/digg.png" alt="Share this page via Digg this" />
</a>
<a target="_blank" href="http://www.facebook.com/sharer.php?u=http%3A%2F%2Fwww.iphonegametutorials.com%2F2012%2F01%2F11%2Fcocos2d-game-tutorial-%25e2%2580%2593-how-to-build-a-tower-defense-game-for-the-iphone-part-5a-multiple-waves%2F&amp;t=How+To+Build+a+Tower+Defense+Game+for+the+iPhone+%E2%80%93+Part+5a+%E2%80%93+Multiple+Waves">
<img src="http://www.iphonegametutorials.com/wp-content/plugins/jw-share-this/fb.png" alt="Share this page via Facebook" />
</a>
<a target="_blank" href="http://twitter.com/intent/tweet?text=I+like+http%3A%2F%2Fwww.iphonegametutorials.com%2F2012%2F01%2F11%2Fcocos2d-game-tutorial-%25e2%2580%2593-how-to-build-a-tower-defense-game-for-the-iphone-part-5a-multiple-waves%2F&amp;title=How+To+Build+a+Tower+Defense+Game+for+the+iPhone+%E2%80%93+Part+5a+%E2%80%93+Multiple+Waves">
<img src="http://www.iphonegametutorials.com/wp-content/plugins/jw-share-this/twitter.png" alt="Share this page via Twitter" />
</a>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.iphonegametutorials.com/2012/01/11/cocos2d-game-tutorial-%e2%80%93-how-to-build-a-tower-defense-game-for-the-iphone-part-5a-multiple-waves/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>10 Pitfalls to Avoid When Making Your Own Indie Game</title>
		<link>http://www.iphonegametutorials.com/2012/01/11/10-pitfalls-to-avoid-when-making-your-own-indie-game/</link>
		<comments>http://www.iphonegametutorials.com/2012/01/11/10-pitfalls-to-avoid-when-making-your-own-indie-game/#comments</comments>
		<pubDate>Wed, 11 Jan 2012 02:20:32 +0000</pubDate>
		<dc:creator>Walter Reid</dc:creator>
				<category><![CDATA[Beginner]]></category>
		<category><![CDATA[Getting Started]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[advice]]></category>
		<category><![CDATA[Analytics]]></category>
		<category><![CDATA[casual game]]></category>
		<category><![CDATA[customer]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[feedback]]></category>
		<category><![CDATA[first game]]></category>
		<category><![CDATA[game art]]></category>
		<category><![CDATA[game design]]></category>
		<category><![CDATA[games market]]></category>
		<category><![CDATA[indie games]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[Marketing]]></category>
		<category><![CDATA[pitfalls]]></category>
		<category><![CDATA[programmer]]></category>
		<category><![CDATA[user interface]]></category>

		<guid isPermaLink="false">http://www.iphonegametutorials.com/?p=579</guid>
		<description><![CDATA[When we started making Drop Dead in late September many years ago, we thought we had enough experience to make a solid, fun game in a short amount of time . We had been working in the casual games market for 4 years before that, we had seen hundreds of casual games, and by that point [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.iphonegametutorials.com/wp-content/uploads/2012/01/iphonepitfalls.png"><img class="alignleft size-medium wp-image-599" title="iphonepitfalls" src="http://www.iphonegametutorials.com/wp-content/uploads/2012/01/iphonepitfalls-300x160.png" alt="" width="300" height="160" /></a>When we started making <a href="http://itunes.apple.com/us/app/drop-dead/id395981508?mt=8">Drop Dead</a> in late September many years ago, we thought we had enough experience to make a solid, fun game in a short amount of time .  We had been working in the casual games market for 4 years before that, we had seen hundreds of casual games, and by that point we had developed a few ourselves at our jobs.  This, however, was our first game to be released by our new company, <a title="Goofball Games" href="http://www.goofballgames.com" target="_blank">Goofball Games</a>, and we were determined to get it right and add it to our portfolio.</p>
<p>The goals were simple &#8211; create a casual game for Halloween that we can show off to prospective clients, but maybe even capitalize on the season and make a few bucks in the process.</p>
<p>So, without further ado, here is a list of 10 pitfalls we either narrowly missed or in some cases fell into head first when making our first iPhone game!<br />
<span id="more-579"></span></p>
<p><strong><strong>Rule #1</strong> &#8211; Don&#8217;t sacrifice quality simple because it&#8217;s your first game.</strong></p>
<p>Game art and music are often overlooked during a rushed development schedule, but 9 out of 9.0001 times it&#8217;s a critical mistake.  Nothing can bring down a good game design faster than &#8220;programmer art&#8221; or no sound in a game.  Think of it this way &#8211; Prior to the point of people *actually paying for your game* they are already judging your work through the screenshots you show in the app store and the description that you write about it.  You know the statement, &#8220;a picture is worth a thousand words&#8221;, well I&#8217;ve seen a ton of games just like this&#8230;.</p>
<div id="attachment_603" class="wp-caption aligncenter" style="width: 160px"><a href="http://www.iphonegametutorials.com/wp-content/uploads/2012/01/320x480-75.jpg"><img class="size-thumbnail wp-image-603 " title="320x480-75" src="http://www.iphonegametutorials.com/wp-content/uploads/2012/01/320x480-75-150x150.jpg" alt="" width="150" height="150" /></a><p class="wp-caption-text">Never played this....</p></div>
<p>One of hundreds of thousands of games found in the iPhone app store&#8230;</p>
<div id="attachment_604" class="wp-caption aligncenter" style="width: 160px"><a href="http://www.iphonegametutorials.com/wp-content/uploads/2012/01/320x480-75-2.jpg"><img class="size-thumbnail wp-image-604 " title="320x480-75-2" src="http://www.iphonegametutorials.com/wp-content/uploads/2012/01/320x480-75-2-150x150.jpg" alt="" width="150" height="150" /></a><p class="wp-caption-text">Or this...</p></div>
<p>Now, I don&#8217;t know about you, but that game and the thousands like it are just looking to be skipped.  This developer might have the world&#8217;s best car handling physics (I doubt it though), but no one will even get to the point of playing it because even in the store it looks terrible.  I almost feel bad about calling that game out, just because I&#8217;m sure the developer put hundreds of hours in.</p>
<p>Seriously, don&#8217;t fall into the trap of thinking that just because you&#8217;re independent that you can&#8217;t produce something of extremely good quality. Yes, it will take you more time to develop than someone with a powerhouse of developers, artists and muscians, but you&#8217;re just going to have to be more creative. If you don&#8217;t like your artistic style, fix it or find someone who works cheap. If your procedural algorithm routines suck, fix them or find someone who can do it better.</p>
<p>All we&#8217;re saying is that if you don&#8217;t want a review on iTunes that says, &#8220;Pass on this one. Looks terrible and plays even worse&#8221;, make sure to put a bit of polish into the game (and the app store page as well).</p>
<p><strong><strong>Rule #2</strong> &#8211; Don’t do ad-based marketing.</strong></p>
<p>This is something we&#8217;ve learned from experience.  When you&#8217;ve made a masterpiece and no one can see it, it&#8217;s a heartbreaking thing.  God knows in my life how many times I&#8217;ve said, &#8220;If I could get someone to just look at my product I know they would love it&#8221;.  So in a fit of desperation you put 50 dollars into an AdMob or one of the 70+ other Ad Networks to sell your 99 cent game.  I guarantee that in a few minutes or hours you&#8217;ll be through that money with only a few clicks as a result and officially $49.50 in the hole.</p>
<p><a href="http://www.iphonegametutorials.com/wp-content/uploads/2012/01/admob.png"><img class="alignleft size-medium wp-image-609" title="admob" src="http://www.iphonegametutorials.com/wp-content/uploads/2012/01/admob-300x179.png" alt="" width="300" height="179" /></a></p>
<p>Don&#8217;t get me wrong!  Once again, there are situations where this doesn&#8217;t need to turn out like this and paying for ads might be the way to go.  Hell, even if you&#8217;re game is 4.99 (or has in-app purchases) it might make more practical sense&#8230; but not much else if your game is 99 cents&#8230; or god forbid it&#8217;s free and you&#8217;re hoping to get your money back through ad support.</p>
<p><strong><strong>Rule #3</strong> &#8211; Do you have a ton of players?  Maybe in-game ads aren&#8217;t for you.</strong></p>
<div id="attachment_611" class="wp-caption alignleft" style="width: 310px"><a href="http://www.iphonegametutorials.com/wp-content/uploads/2012/01/mobile-advertising-marketing-feature.jpg"><img class="size-medium wp-image-611" title="mobile-advertising-marketing-feature" src="http://www.iphonegametutorials.com/wp-content/uploads/2012/01/mobile-advertising-marketing-feature-300x240.jpg" alt="" width="300" height="240" /></a><p class="wp-caption-text">Does your ad really need to cover everything?</p></div>
<p>Maybe your game isn&#8217;t selling well or maybe you feel like offering a free &#8220;ad supported&#8221; version of the game.  Adding ads to support the project &#8211; especially &#8211; when it hasn&#8217;t been planned from the start &#8211; is just not worth it.  Don&#8217;t get me wrong, there are games that make money with AdMob and the like, but the other 99.997 percent of indie developers will not even make the minimum to get paid out.  When you have 100k active and dedicated players of your game, then you can make the deals through sponsorship and ad buys, but if you&#8217;re starting out, it&#8217;s just better to stay true to the game.<br />
The worst, I mean the worst, is when you decide to add new ads into a game that wasn&#8217;t built to support ads.  We&#8217;ve definitely been there before&#8230;</p>
<p>Even if the view isn&#8217;t obstructed by some terrible and unrelated ad, it still most likely won&#8217;t be clicked on and has the very real potential of sucking the player out of the game.  Something you don&#8217;t want from a very real customer, who might have had a better experience with a non-ad supported version and actually bought the game.</p>
<p>Risk alienating a few players after you have more than enough to spare.  What number is that?  I don&#8217;t know yet.  Maybe someone in the comments will have a good answer <img src='http://www.iphonegametutorials.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':-D' class='wp-smiley' /> </p>
<p><strong><strong>Rule #4</strong> &#8211; Release, update, update, update aaaaand update</strong></p>
<p>Personally, I am a firm believer in having a roll out schedule after the first major release.  You need to keep people playing your game while at the same time building the next one. Rovio (creators of Angry Birds) have built a $2 billion company out of some lovable characters and additional new content.  Can you name another company that has done that? Does Disney sound familiar? Remember content is king and if you want to rule, give the people what they want.  I know, I know, it&#8217;s hard to do this for free, but on a long enough timeline it could pay dividends.</p>
<p><a href="http://www.iphonegametutorials.com/wp-content/uploads/2012/01/farmville-iphone-app-update.jpg"><img class="alignleft size-medium wp-image-618" title="farmville-iphone-app-update" src="http://www.iphonegametutorials.com/wp-content/uploads/2012/01/farmville-iphone-app-update-300x247.jpg" alt="" width="300" height="247" /></a></p>
<p>Dedicated fans can be your best friends in the world, so don&#8217;t ignore their suggestions and comments (iPhoneGameTutorials.com could learn this lesson again).  Here are a few things you can do in your game to empower your players and have them stay around longer:</p>
<p>1. Update your content regularly &#8211; Put in additional levels and/or new content on a weekly or bi-weekly basis!  You game isn&#8217;t level based?  Then fix the bugs!<br />
2. Give users a place to communicate about your game and to offer their feedback &#8211; Don&#8217;t force them to have a conversation through their ratings<br />
3. Add passive achievements and badging to your game &#8211; give people a reason to keep your game installed for months<br />
4. Put in sharing features for Twitter and/or Facebook for easy sharing &#8211; people usually have similar friends, those similar friends might download your game.</p>
<p>If it wasn&#8217;t for some loyal readers comments these last few months, our site would be all but barren.  So remember, keep the people who keep coming back happy &#8211; give them what they want: <span style="text-decoration: line-through;">tons of porn </span> [Editor's Note: I think he means <strong>CONTENT</strong>].</p>
<p><strong><strong>Rule #5</strong> &#8211; Remember the importance of having a good time during development</strong></p>
<p>If I could only post one rule more than once&#8230; this might be it!</p>
<p>You may not know it yet, but making an awesome product is seriously hard work.  When you&#8217;re pushing to meet deadlines the business of games can be an uphill battle the whole way.  No one has ever said love is easy and doing something by yourself that you love is no less difficult.  Always keep in mind the reason you&#8217;re building the game you are and don&#8217;t sweat the small stuff as it were.</p>
<p><a href="http://www.iphonegametutorials.com/wp-content/uploads/2012/01/motivation.jpg"><img class="alignleft size-medium wp-image-614" title="motivation" src="http://www.iphonegametutorials.com/wp-content/uploads/2012/01/motivation-300x251.jpg" alt="" width="300" height="251" /></a></p>
<p>One way to do this is to work within the framework of small goals.  They allow you create a feedback cycle with yourself. Code a little, debug a little, feel good to see your game doing a little bit more cool stuff. The worst parts of any development are the big things that take a long time to finish, because you risk losing that joy of accomplishment while you work on it.</p>
<p><strong>Rule #6</strong> <strong>- Don’t re-invent the wheel, or the game engine.</strong></p>
<p><strong> </strong>It&#8217;s very easy to focus too much on developing the framework or game engine, and too little about making the actual game.  You risk getting all entangled up in the nitty gritty and never actually get around to actually building anything.</p>
<p>You&#8217;ll notice we use Cocos2d (<a title="Cocos2D Download Page" href="http://www.cocos2d-iphone.org/download" target="_blank">download</a>) on this site a ton of times, because it works for the games we want to create.  Could we create our own OpenGL wrapper game engine? Sure we could, but what&#8217;s the point when there are already some fantastic packages with established communities!   Currently there are several open source game engines to choose from, and many cropping up all the time.  Our advice is<a href="http://www.iphonegametutorials.com/2010/09/02/iphone-game-development-getting-started/" target="_blank"> take a look at some of the packages we go over</a> on this site or type &#8220;iPhone Game Engines&#8221; and you&#8217;ll find a million and one comparisons.</p>
<p>Never forget you are first and foremost making a game &#8211; not a middle-ware component.  You should not start by coding the math library but instead by figuring out how to make the game entertaining.</p>
<p><strong><strong>Rule #7</strong> &#8211; The work you do after you finish development is just as important as building the game itself.</strong></p>
<p>You should push your game whenever you can. Why? Because you&#8217;re indie. Nobody knows you.  You absolutely need to get yourself out and start building your brand as early as you possibly can. You can&#8217;t expect to have the next big hit, so you need to start dipping your toes into the water early. Marketing is hard, but so is building a game and you&#8217;ve already started that &#8211; just go a little farther!</p>
<p><a href="http://www.iphonegametutorials.com/wp-content/uploads/2012/01/social-media-marketing.jpg"><img class="alignleft size-medium wp-image-615" title="social-media-marketing" src="http://www.iphonegametutorials.com/wp-content/uploads/2012/01/social-media-marketing-300x215.jpg" alt="" width="300" height="215" /></a></p>
<p>Building a brand can be a full-time position. Spend an hour or two everyday talking to your community or other people to help them discover you.  Above all else, be proud of the work you&#8217;ve put into your game and continue to put into it.  So, if you create something, show it off, tell people about it, talk about it whenever you can &#8211; you&#8217;ve put weeks or months into it&#8230; be proud.</p>
<p><strong>Rule #8</strong><strong> &#8211; Analytics (know how your audience plays your game).</strong></p>
<p><strong> </strong>How many people have played your game today?  How many people turned off the sound?  How many people turned off the music?  How many people played and lost level 17?  You should know this. Don&#8217;t let analytics fall into a &#8220;nice to have&#8221; category.  After you&#8217;ve released the the app and people are installing it around the globe, the usage metrics can be some of the most informative information about how people are using your game and where you can make improvements.</p>
<p><strong><strong>Rule #9</strong> &#8211; The value in adorable/cute/sweet/awesome characters</strong></p>
<p>The more I watch, read and learn the more I realize the power of cute.</p>
<div id="attachment_620" class="wp-caption alignleft" style="width: 304px"><a href="http://www.iphonegametutorials.com/wp-content/uploads/2012/01/Angry-Birds-Plush.jpg"><img class="size-medium wp-image-620" title="Angry Birds Plush" src="http://www.iphonegametutorials.com/wp-content/uploads/2012/01/Angry-Birds-Plush-294x300.jpg" alt="" width="294" height="300" /></a><p class="wp-caption-text">Aww, how cute... and so very angry</p></div>
<p>Rovio is making a killing this way &#8211; did you know they opened their first store dedicated to their plush stuffed characters in Helsinki, Finland?  This really does come back to the idea of polish &#8211; you need to make a game that really is not just fun to play, but is something that will make people feel comfortable sharing with their friends.  Or paying $15.99 for a stuffed green pig.</p>
<p><strong>Rule #10</strong> <strong>- Prefer game concepts / game updates which have a fast development time</strong><br />
Experience / Experience / Experience&#8230; As you roll out new versions or even new games entirely, keep in mind the development time.  Your game is competing against big and small alike and it&#8217;s better to do the job right once with a good amount of planning than to bite off more than you can chew.  So instead of improving the core mechanic and seeing how your fans react, you spend 6 months trying to get every last feature into release 2.0. This will alienate your users and most likely the game will float out of their consciousness and off of their phones!</p>
<p>So, what are your thoughts about the biggest mistakes an indie game developer can make? Have you ran into any of these or have ways to avoid them? Tell us in the comments below!</p>

<div class="jwsharethis">
Share this: 
<br />
<a href="mailto:?subject=10%20Pitfalls%20to%20Avoid%20When%20Making%20Your%20Own%20Indie%20Game&amp;body=http%3A%2F%2Fwww.iphonegametutorials.com%2F2012%2F01%2F11%2F10-pitfalls-to-avoid-when-making-your-own-indie-game%2F">
<img src="http://www.iphonegametutorials.com/wp-content/plugins/jw-share-this/email.png" alt="Share this page via Email" />
</a>
<a target="_blank" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.iphonegametutorials.com%2F2012%2F01%2F11%2F10-pitfalls-to-avoid-when-making-your-own-indie-game%2F&amp;title=10+Pitfalls+to+Avoid+When+Making+Your+Own+Indie+Game">
<img src="http://www.iphonegametutorials.com/wp-content/plugins/jw-share-this/su.png" alt="Share this page via Stumble Upon" />
</a>
<a target="_blank" href="http://digg.com/submit?url=http%3A%2F%2Fwww.iphonegametutorials.com%2F2012%2F01%2F11%2F10-pitfalls-to-avoid-when-making-your-own-indie-game%2F&amp;title=10+Pitfalls+to+Avoid+When+Making+Your+Own+Indie+Game">
<img src="http://www.iphonegametutorials.com/wp-content/plugins/jw-share-this/digg.png" alt="Share this page via Digg this" />
</a>
<a target="_blank" href="http://www.facebook.com/sharer.php?u=http%3A%2F%2Fwww.iphonegametutorials.com%2F2012%2F01%2F11%2F10-pitfalls-to-avoid-when-making-your-own-indie-game%2F&amp;t=10+Pitfalls+to+Avoid+When+Making+Your+Own+Indie+Game">
<img src="http://www.iphonegametutorials.com/wp-content/plugins/jw-share-this/fb.png" alt="Share this page via Facebook" />
</a>
<a target="_blank" href="http://twitter.com/intent/tweet?text=I+like+http%3A%2F%2Fwww.iphonegametutorials.com%2F2012%2F01%2F11%2F10-pitfalls-to-avoid-when-making-your-own-indie-game%2F&amp;title=10+Pitfalls+to+Avoid+When+Making+Your+Own+Indie+Game">
<img src="http://www.iphonegametutorials.com/wp-content/plugins/jw-share-this/twitter.png" alt="Share this page via Twitter" />
</a>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.iphonegametutorials.com/2012/01/11/10-pitfalls-to-avoid-when-making-your-own-indie-game/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Steve Jobs, an Innovator and Entrepreneur, Rest in Peace.</title>
		<link>http://www.iphonegametutorials.com/2011/10/06/rip-steve-jobs/</link>
		<comments>http://www.iphonegametutorials.com/2011/10/06/rip-steve-jobs/#comments</comments>
		<pubDate>Thu, 06 Oct 2011 18:09:15 +0000</pubDate>
		<dc:creator>Walter Reid</dc:creator>
				<category><![CDATA[News]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[apple]]></category>
		<category><![CDATA[ceo]]></category>
		<category><![CDATA[computer landscape]]></category>
		<category><![CDATA[iPad]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[laptop]]></category>
		<category><![CDATA[legacy]]></category>
		<category><![CDATA[macintosh]]></category>
		<category><![CDATA[next computer]]></category>
		<category><![CDATA[personal computers]]></category>
		<category><![CDATA[rip]]></category>
		<category><![CDATA[steve jobs]]></category>
		<category><![CDATA[timeline]]></category>

		<guid isPermaLink="false">http://www.iphonegametutorials.com/?p=561</guid>
		<description><![CDATA[“The people who are crazy enough to think they can change the world, are the ones who do.” – Apple Inc. We felt that it was important to mention Steve Jobs on our site today &#8211; a site based on the great devices and technology he pioneered. We are all very sad at the passing [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.iphonegametutorials.com/wp-content/uploads/2011/10/steve-jobs-apple-ceo-dies-0.jpg"><img src="http://www.iphonegametutorials.com/wp-content/uploads/2011/10/steve-jobs-apple-ceo-dies-0.jpg" alt="" title="steve-jobs-apple-ceo-dies-0" width="200" height="200" class="alignleft size-full wp-image-562" /></a>“The people who are crazy enough to think they can change the world, are the ones who do.”<br />
– Apple Inc.</p>
<p>We felt that it was important to mention Steve Jobs on our site today &#8211; a site based on the great devices and technology he pioneered.  We are all very sad at the passing of a man who was a designer first and a CEO second.  </p>
<p>Now, I&#8217;ve been using Apple products virtually my entire life (starting with my Apple II) and have been amazed that with each new product released the bar has been continually raised.  At our offices today we have multiple Macbook Pros, iPods, iPhones and iPads on virtually every work surface.  This is not just because we do development with these devices, but because we genuinely enjoy using these products and find them to be essential in our personal lives as well.  So, we&#8217;ve put together a list of influential years in Steve Job&#8217;s life that we think exemplify how much he has changed the personal computer, mobile and tablet landscape over the years:</p>
<p>1977: First Successful Personal Computer<br />
1984: The Macintosh<br />
1985: NeXT Computer &#8211; Jobs starts again.<br />
1996: Apple buys NeXT and makes Jobs CEO again.<br />
2000: Jobs introduces a new way of thinking about design for personal computers<br />
2001: The iPod.<br />
2006: Jobs redefines the laptop with the MacBook<br />
2007: iPhone makes its debut<br />
2010: The iPad brings tablets to the foreground.</p>
<p>For a man who helped create so much, we would like to thank him for his contributions and look forward to Apple continuing his legacy of great products in the years to come.</p>
<p>Sincerely,<br />
iPhoneGameTutorials</p>

<div class="jwsharethis">
Share this: 
<br />
<a href="mailto:?subject=Steve%20Jobs%2C%20an%20Innovator%20and%20Entrepreneur%2C%20Rest%20in%20Peace.&amp;body=http%3A%2F%2Fwww.iphonegametutorials.com%2F2011%2F10%2F06%2Frip-steve-jobs%2F">
<img src="http://www.iphonegametutorials.com/wp-content/plugins/jw-share-this/email.png" alt="Share this page via Email" />
</a>
<a target="_blank" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.iphonegametutorials.com%2F2011%2F10%2F06%2Frip-steve-jobs%2F&amp;title=Steve+Jobs%2C+an+Innovator+and+Entrepreneur%2C+Rest+in+Peace.">
<img src="http://www.iphonegametutorials.com/wp-content/plugins/jw-share-this/su.png" alt="Share this page via Stumble Upon" />
</a>
<a target="_blank" href="http://digg.com/submit?url=http%3A%2F%2Fwww.iphonegametutorials.com%2F2011%2F10%2F06%2Frip-steve-jobs%2F&amp;title=Steve+Jobs%2C+an+Innovator+and+Entrepreneur%2C+Rest+in+Peace.">
<img src="http://www.iphonegametutorials.com/wp-content/plugins/jw-share-this/digg.png" alt="Share this page via Digg this" />
</a>
<a target="_blank" href="http://www.facebook.com/sharer.php?u=http%3A%2F%2Fwww.iphonegametutorials.com%2F2011%2F10%2F06%2Frip-steve-jobs%2F&amp;t=Steve+Jobs%2C+an+Innovator+and+Entrepreneur%2C+Rest+in+Peace.">
<img src="http://www.iphonegametutorials.com/wp-content/plugins/jw-share-this/fb.png" alt="Share this page via Facebook" />
</a>
<a target="_blank" href="http://twitter.com/intent/tweet?text=I+like+http%3A%2F%2Fwww.iphonegametutorials.com%2F2011%2F10%2F06%2Frip-steve-jobs%2F&amp;title=Steve+Jobs%2C+an+Innovator+and+Entrepreneur%2C+Rest+in+Peace.">
<img src="http://www.iphonegametutorials.com/wp-content/plugins/jw-share-this/twitter.png" alt="Share this page via Twitter" />
</a>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.iphonegametutorials.com/2011/10/06/rip-steve-jobs/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

