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

Coloring sprites


In the previous recipe we used colored rectangles to draw both the ground and the sky. The ability to set texture color and opacity are simple tools which, if used properly, can create very cool effects. In this recipe we will create a cinematic scene where two samurai face each other with glowing swords.

Getting ready

Please refer to the project RecipeCollection01 for full working code of this recipe. Also, note that some code has been omitted for brevity.

How to do it...

Execute the following code:

#import "CCGradientLayer.h

@implementation Ch1_ColoringSprites

-(CCLayer*) runRecipe {
  [self initButtons];
  
  //The Fade Scene Sprite
  CCSprite *fadeSprite = [CCSprite spriteWithFile:@"blank.png"];
  [fadeSprite setOpacity:0];
  [fadeSprite setPosition:ccp(240,160)];
  [fadeSprite setTextureRect:CGRectMake(0,0,480,320)];
  [self addChild:fadeSprite z:3 tag:TAG_FADE_SPRITE];
  
  //Add a gradient below the mountains
//CCGradientDirectionT_B is an enum provided by CCGradientLayer
  CCGradientLayer *gradientLayer = [CCGradientLayer layerWithColor:
 ccc4(61,33,62,255) toColor:ccc4(65,89,54,255) withDirection:CCGradientDirectionT_B width:480 height:100];
  [gradientLayer setPosition:ccp(0,50)];
  [self addChild:gradientLayer z:0 tag:TAG_GROUND_GRADIENT];

  //Add a sinister red glow gradient behind the evil samurai
  CCGradientLayer *redGradient = [CCGradientLayer
 layerWithColor:ccc4(0,0,0,0) toColor:ccc4(255,0,0,100)
 withDirection:CCGradientDirectionT_B width:200 height:200];
  [redGradient setPosition:ccp(280,60)];
  [redGradient setRotation:-90];
  [self addChild:redGradient z:2 tag:TAG_RED_GRADIENT];
  
  // Make the swords glow
  [self glowAt:ccp(230,280) withScale:CGSizeMake(3.0f, 11.0f)
  withColor:ccc3(0,230,255) withRotation:45.0f withSprite:goodSamurai];
  [self glowAt:ccp(70,280) withScale:CGSizeMake(3.0f, 11.0f)
  withColor:ccc3(255,200,2) withRotation:-45.0f withSprite:evilSamurai];
  
  return self;  
}

-(void) initButtons {
  [CCMenuItemFont setFontSize:16];

  //'Fade To Black' button
  CCMenuItemFont* fadeToBlack = [CCMenuItemFont itemFromString:@"FADE TO BLACK"
 target:self selector:@selector(fadeToBlackCallback:)];
  CCMenu *fadeToBlackMenu = [CCMenu menuWithItems:fadeToBlack, nil];
    fadeToBlackMenu.position = ccp( 180 , 20 );
    [self addChild:fadeToBlackMenu z:4 tag:TAG_FADE_TO_BLACK];  
}

/* Fade the scene to black */
-(void) fadeToBlackCallback:(id)sender {
  CCSprite *fadeSprite = [self getChildByTag:TAG_FADE_SPRITE];
  [fadeSprite stopAllActions];
  [fadeSprite setColor:ccc3(0,0,0)];
  [fadeSprite setOpacity:0.0f];
  [fadeSprite runAction: 
  [CCSequence actions:[CCFadeIn actionWithDuration:2.0f], [CCFadeOut actionWithDuration:2.0f], nil] ];  
}

/* Create a glow effect */
-(void) glowAt:(CGPoint)position withScale:(CGSize)size
withColor:(ccColor3B)color withRotation:(float)rotation
withSprite:(CCSprite*)sprite {
  CCSprite *glowSprite = [CCSprite spriteWithFile:@"fire.png"];
  [glowSprite setColor:color];
  [glowSprite setPosition:position];
  [glowSprite setRotation:rotation];
  [glowSprite setBlendFunc: (ccBlendFunc) { GL_ONE, GL_ONE }];
  [glowSprite runAction: [CCRepeatForever actionWithAction:
    [CCSequence actions:[CCScaleTo actionWithDuration:0.9f
   scaleX:size.width scaleY:size.height], [CCScaleTo
   actionWithDuration:0.9f scaleX:size.width*0.75f
   scaleY:size.height*0.75f], nil] ] ];  
  [glowSprite runAction: [CCRepeatForever actionWithAction:
    [CCSequence actions:[CCFadeTo actionWithDuration:0.9f opacity:150], [CCFadeTo actionWithDuration:0.9f opacity:255], nil] ] ];  
    
  [sprite addChild:glowSprite];
}

@end

How it works...

This recipe shows a number of color based techniques.

  • Setting sprite color:

    The simplest use of color involves setting the color of a sprite using the following method:

    -(void) setColor:(ccColor3B)color;

    Setting sprite color effectively reduces the color you can display but it allows some programmatic flexibility in drawing. In this recipe we use setColor for a number of things, including drawing a blue sky, a yellow sun, black "dramatic movie bars", and more.

    ccColor3B is a C struct which contains three GLubyte variables. Use the following helper macro to create ccColor3B structures:

    ccColor3B ccc3(const GLubyte r, const GLubyte g, const GLubyte b);

    Cocos2d also specifies a number of pre-defined colors as constants. These include the following:

    ccWHITE, ccYELLOW, ccBLUE, ccGREEN, ccRED, 
    ccMAGENTA, ccBLACK, ccORANGE, ccGRAY
  • Fading to a color:

    To fade a scene to a specific color we use the blank.png technique we went over in the last recipe. We first draw a sprite as large as the screen, then color the sprite to the color we want to fade to, and then finally run a CCFadeIn action on the sprite to fade to that color:

    [fadeSprite setColor:ccc3(255,255,255)];
    [fadeSprite setOpacity:0.0f];
    [fadeSprite runAction: [CCFadeIn actionWithDuration:2.0f] ];
  • Using CCGradientLayer:

    Using the CCGradientLayer class we can programmatically create gradients. To make the mountains in the background fade into the ground the two samurai are standing on we created a gradient using this method:

      CCGradientLayer *gradientLayer = [CCGradientLayer layerWithColor:ccc4(61,33,62,255) toColor:ccc4(65,89,54,255) withDirection:CCGradientDirectionT_B width:480 height:100];
      [gradientLayer setPosition:ccp(0,50)];
      [self addChild:gradientLayer z:0 tag:TAG_GROUND_GRADIENT];

    Because CCGradientLayer lets you control opacity as well as color, it has many uses. As you can see there is also a sinister red glow behind the evil samurai.

  • Making a sprite glow:

    To make the swords in the demo glow we use subtle color manipulation, additive blending and fading and scaling actions. First we load the fire.png sprite supplied by Cocos2d. By changing its X and Y scale independently we can make it thinner or fatter. Once you have the desired scale ratio (in this demo we use x:y 3:11 because the sword is so thin) you can constantly scale and fade the sprite in and out to give some life to the effect. You also need to set the blend function to { GL_ONE, GL_ONE } for additive blending. Finally this effect sprite is added to the actual sprite to make it seem like it glows.

    CCSprite *glowSprite = [CCSprite spriteWithFile:@"fire.png"];
      [glowSprite setColor:color];
      [glowSprite setPosition:position];
      [glowSprite setRotation:rotation];
      [glowSprite setBlendFunc: (ccBlendFunc) { GL_ONE, GL_ONE }];
      [glowSprite runAction: [CCRepeatForever actionWithAction:
      [CCSequence actions:[CCScaleTo actionWithDuration:0.9f
      scaleX:size.width scaleY:size.height], [CCScaleTo
      actionWithDuration:0.9f scaleX:size.width*0.75f
      scaleY:size.height*0.75f], nil] ] ];  
      [glowSprite runAction: [CCRepeatForever actionWithAction:
      [CCSequence actions:[CCFadeTo actionWithDuration:0.9f opacity:150], [CCFadeTo actionWithDuration:0.9f opacity:255], nil] ] ];    
      [sprite addChild:glowSprite];