Book Image

Cocos2d for iPhone 1 Game Development Cookbook

By : Nathan Burba
Book Image

Cocos2d for iPhone 1 Game Development Cookbook

By: Nathan Burba

Overview of this book

Cocos2d for iPhone is a robust but simple-to-use 2D game framework for iPhone. It is easy to use, fast, flexible, free, and Appstore approved. More than 2500 AppStore games already use it, including many best-seller games. Do you want to take your cocos2d game development skills to the next level and become more professional in cocos2d game design? Cocos2d for iPhone 1 Game Development Cookbook will help you reach that next level. You will find over 100 recipes here that explain everything from the drawing of a single sprite to AI pathfinding and advanced networking. Full working examples are emphasized. Starting with the first chapter, Graphics, you will be taken through every major topic of game development. You will find both simple and complex recipes in the book. Each recipe is either a solution to a common problem (playing video files, accelerometer steering) or a cool advanced technique (3D rendering, textured polygons). This cookbook will have you creating professional quality iOS games quickly with its breadth of working example code.
Table of Contents (15 chapters)
Cocos2d for iPhone 1 Game Development Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Grid, particle, and motion streak effects


Cocos2d comes equipped with a variety of easy to use special effects. Here, we will only briefly go over all of the effects as they are fairly straightforward and are well covered in other texts.

Getting ready

Please refer to the project RecipeCollection01 for full working code of this recipe.

How to do it...

To get grid effects to show up properly in your game you first need to set the EAGLView pixelFormat to kEAGLColorFormatRGBA8 (it is set to kEAGLColorFormatRGB565 by default).

Do this by going into your project file's ${PROJECT_NAME}AppDelegate.m file and changing the following code:

  EAGLView *glView = [EAGLView viewWithFrame:[window bounds]
                   pixelFormat: kEAGLColorFormatRGB565
                   depthFormat:0            
            ];

Change it to this:

  EAGLView *glView = [EAGLView viewWithFrame:[window bounds]
                   pixelFormat: kEAGLColorFormatRGBA8
                   depthFormat:0            
            ];

Then, execute the following code:

//Custom particle effect
@implementation ParticleWaterfall

-(id)init {
  return [self initWithTotalParticles:400];
}
-(id)initWithTotalParticles:(int)p {
  if(self != [super initWithTotalParticles: p])
    return nil;

  //Angle
  angle = 270;
  angleVar = 12;

  //Emitter position
  self.position = ccp(160, 60);
  posVar = ccp(16, 4);

  //Life of particles
  life = 2;
  lifeVar = 0.25f;

  //Speed of particles
  self.speed = 100;
  self.speedVar = 20;
  self.gravity = ccp(self.gravity.x, -5);

  //Size of particles
  startSize = 35.0f;
  endSize = 100.0f;

  //Color of particles
  startColor = ccc4(0.4f, 0.4f, 1.0f, 0.6f);
  startColorVar = ccc4(0,0,0,0);
  endColor = ccc4(0.5f, 0.5f, 0.5f, 0);
  endColorVar = ccc4(0,0,0,0);

  //Additive
  self.blendAdditive = NO;

  return self;
}

@end

@interface Ch1_GridParticleMotionEffects
{
  //Variables for motion streak effect
  CCSprite *rocket;
  CCMotionStreak *streak;
  CGPoint rocketDirection;
}

@implementation Ch1_GridParticleMotionEffects

-(CCLayer*) runRecipe {
  CGSize s = [[CCDirector sharedDirector] winSize];

  /*** Grid effect demo ***/

  //Create a CCSprite
  CCSprite *sprite = [CCSprite spriteWithFile:@"colorable_sprite.png"];
  [sprite setPosition:ccp(240,160)];
  [self addChild:sprite z:1 tag:TAG_SPRITE];
  
  //Create a grid effect
  CCAction *gridEffect = [CCShaky3D actionWithRange:5 shakeZ:YES grid:ccg(15,10) duration:10];

  //Run the effect
  [sprite runAction:gridEffect];

  /*** Particle effect demo ***/
  
//Create a simple fire particle effect
CCNode *fireEffect = [CCParticleFire node];
[self addChild:fireEffect z:1 tag:TAG_FIRE_EFFECT];

  //Create a waterfall particle effect
  CCNode *waterfallEffect = [ParticleWaterfall node];
  [self addChild:waterfallEffect z:1 tag:TAG_WATERFALL_EFFECT];

  /*** Motion streak demo ***/
  
  //Set the rocket initially in a random direction.
  rocketDirection = ccp(arc4random()%4+1,arc4random()%4+1);
    
  //Add the rocket sprite.
  rocket = [CCSprite spriteWithFile:@"rocket.png"];
  [rocket setPosition:ccp(s.width/2, s.height/2)];
  [rocket setScale:0.5f];
  [self addChild:rocket];
    
  //Create the streak object and add it to the scene.
  streak = [CCMotionStreak streakWithFade:1 minSeg:1 image:@"streak.png" width:32 length:32 color:ccc4(255,255,255,255)];
  [self addChild:streak];
  
  streak.position = ccp(s.width/2, s.height/2);

  [self schedule:@selector(step:)];

  return self;
}

-(void)step:(ccTime)delta {
  CGSize s = [[CCDirector sharedDirector] winSize];

  //Make rocket bounce off walls
  if(rocket.position.x > s.width || rocket.position.x < 0){
    rocketDirection = ccp(-rocketDirection.x, rocketDirection.y);
  }
  else if(rocket.position.y > s.height || rocket.position.y < 0){
    rocketDirection = ccp(rocketDirection.x, -rocketDirection.y);
  }

  //Slowly turn the rocket
  rocketDirection = ccp(rocketDirection.x, rocketDirection.y+0.05f);

  //Update rocket position based on direction
  rocket.position = ccp(rocket.position.x + rocketDirection.x, rocket.position.y + rocketDirection.y);
  [streak setPosition:rocket.position];

  //Set the rocket's rotation  
  [rocket setRotation: radiansToDegrees(vectorToRadians(rocketDirection))];
}

@end

How it works...

In this recipe we see a number of things. For the sake of brevity I've only included one grid effect and two particle effects in the book. Every stock grid and particle effect is viewable in RecipeCollection01, along with some customized particle effects like Waterfall and WaterSplash.

  • Custom Particles:

    Cocos2d particles have many variables and it is most often advantageous to sub-class a built-in particle to help create your own. Here is a list of the built-in Cocos2d particles:

        CCParticleExplosion, CCParticleFire, CCParticleFireworks,
      CCParticleFlower, CCParticleGalaxy, CCParticleMeteor,
      CCParticleRain, CCParticleSmoke, CCParticleSnow,
      CCParticleSpiral, CCParticleSun
  • Using CCMotionStreak:

    A motion streak is a great way to add a dynamic element a CCNode. These can often be combined with particles for a great effect.

    One thing to keep in mind when creating a motion streak is that the texture needs to look good when it bends in on itself. Vertical textures with transparent gradient edges usually look the best.