2012年6月22日 星期五

Cocos2D 2.0 Tiled Grid Effects


Effects are special kinds of actions. Instead of modifying normal properties like opacitypositionrotation, or scale, they modify a new kind of property: the grid property.


grid property is like a matrix, it is a network of lines that cross each other to form a series of squares or rectangles.


The grids have 2 dimensions: rows and columns, but each vertex of the grid has 3 dimension: x, y and z. So you can create 2d or 3d effects by transforming a tiled-grid-3D grid.


tiled-grid-3D of size (3, 2)
Each frame the screen is rendered into a texture. This texture is transformed into a vertex array and this vertex array (the grid!) is transformed by the grid effects. Finally the vertex array is rendered into the screen.

Enable 3D Projection

    [director setProjection:kCCDirectorProjection3D];

Tiled Grid 3D Actions

  • CCFadeOutBLTiles
          Fades out the tiles in a Bottom-Left direction.

          example:
      id effect = [CCFadeOutBLTiles actionWithSize:ccg(32, 24) duration:3];
      [mySprite runAction:effect];
  • CCFadeOutDownTiles
          Fades out the tiles in downwards direction.


          example:
      id effect = [CCFadeOutDownTiles actionWithSize:ccg(32, 24) duration:3];
      [mySprite runAction:effect];
  • CCFadeOutTRTiles
          Fades out the tiles in a Top-Right direction.


          example:
      id effect = [CCFadeOutTRTiles actionWithSize:ccg(32, 24) duration:3];

      [mySprite runAction:effect];
  • CCFadeOutUpTiles
          Fades out the tiles in upwards direction.


          example:
      id effect = [CCFadeOutUpTiles actionWithSize:ccg(32, 24) duration:3];

      [mySprite runAction:effect];
  • CCFadeIutDownTiles
          Fades out the tiles in downwards direction.


          example:
      id effect = [CCFadeOutDownTiles actionWithSize:ccg(32, 24) duration:3];

      [mySprite runAction:effect];
  • CCJumpTiles3D
          A sin function is executed to move the tiles across the Z axis.


          example:
      id effect = [CCJumpTiles3D actionWithJumps:6 amplitude:20 grid:ccg(32, 24) duration:3];
      [mySprite runAction:effect];
  • CCShakyTiles3D
          Shaky the tiles.


          example:
      id effect = [CCShakyTiles3D actionWithRange:2 shakeZ:YES grid:ccg(32, 24) duration:3];
      [mySprite runAction:effect];
  • CCShatteredTiles3D
          Shatter the tiles.


          example:
      id effect = [CCShatteredTiles3D actionWithRange:2 shatterZ:YES grid:ccg(9, 9) duration:3];
      [mySprite runAction:effect];

  • CCShuffleTiles
          Shuffle the tiles.


          example:

    id effect = [CCShuffleTiles actionWithSeed:1 grid:ccg(32, 24) duration:3];
     [mySprite runAction:effect];
  • CCSplitCols
          Split the node in columns.

          example:
      id effect = [CCSplitCols actionWithCols:20 duration:3];
      [mySprite runAction:effect];

  • CCSplitRows
          Split the node in rows.

          example:

      id effect = [CCSplitRows actionWithRows:6 duration:3];
      [mySprite runAction:effect];
  • CCTurnOffTiles
          Turn off the tiles

          example:
      id effect = [CCTurnOffTiles actionWithSeed:3 grid:ccg(32, 24) duration:3];
      [mySprite runAction:effect];
  • CCWavesTiles3D
          Add 3d waves effect to the tiles.

          example:
      id effect = [CCWavesTiles3D actionWithWaves:10 amplitude:6 grid:ccg(32, 24) duration:3];
      [mySprite runAction:effect];

2012年6月21日 星期四

Cocos2d 2.0 Grid Effects

Effects are special kinds of actions. Instead of modifying normal properties like opacitypositionrotation, or scale, they modify a new kind of property: the grid property.


grid property is like a matrix, it is a network of lines that cross each other to form a series of squares or rectangles.


The grids have 2 dimensions: rows and columns, but each vertex of the grid has 3 dimension: x, y and z. So you can create 2d or 3d effects by transforming a grid-3D grid.


A grid-3D of size (3, 2)

Each frame the screen is rendered into a texture. This texture is transformed into a vertex array and this vertex array (the grid!) is transformed by the grid effects. Finally the vertex array is rendered into the screen.

Enable 3D Projection

    [director setProjection:kCCDirectorProjection3D];

Grid 3D Actions

  • CCFlipX3D
          Flip the node over X-Axis.

          example:

      id effect = [CCFlipX3D actionWithDuration:3];
      [mySprite runAction:effect];
  • CCFlipY3D
          Flip the node over Y-Axis.

          example:
      id effect = [CCFlipY3D actionWithDuration:3];
      [mySprite runAction:effect];
  • CCLens3D
          Add 3d lens effect on the node.

          example:
      CGSize winSize = [[CCDirector sharedDirector] winSize];
      id effect = [CCLens3D actionWithPosition:ccp(winSize.width / 2, winSize.height / 2) radius:90 grid:ccg(32, 24) duration:0];

     [mySprite runAction:effect];
  • CCLiquid
          Add liquid wave effect to the node.

          example:
      id effect = [CCLiquid actionWithWaves:10 amplitude:5 grid:ccg(32, 24) duration:3];
     [mySprite runAction:effect];
  • CCRipple3D
          Add 3d ripple effect to the node.

          example:
      CGSize winSize = [[CCDirector sharedDirector] winSize];
      id effect = [CCRipple3D actionWithPosition:ccp(winSize.width / 2, winSize.height / 2) radius:180 waves:10 amplitude:10 grid:ccg(32, 24) duration:3];
      [mySprite runAction:effect]; 
  • CCShaky3D
          Add 2d/3d shaky effect to the node.


          example:
      id effect = [CCShaky3D actionWithRange:3 shakeZ:YES grid:ccg(32, 24) duration:3];
      [mySprite runAction:effect]; 
  • CCTwirl
          Add twirl effect to the node.

          example:
      CGSize winSize = [[CCDirector sharedDirector] winSize];
      id effect = [CCTwirl actionWithPosition:ccp(winSize.width / 2, winSize.height / 2) twirls:6 amplitude:2 grid:ccg(32, 24) duration:3];
      [mySprite runAction:effect];
  • CCWaves
          Add 2d waves effect to the node.

          example:
      id effect = [CCWaves actionWithWaves:15 amplitude:5 horizontal:YES vertical:YES grid:ccg(32, 24) duration:3];
      [mySprite runAction:effect];
  • CCWaves3D
          Add 3d waves effect to the node.


          example:
      id effect = [CCWaves3D actionWithWaves:5 amplitude:15 grid:ccg(32, 24) duration:3];
      [mySprite runAction:effect];

2012年6月20日 星期三

Cocos2d 2.0 Animation

To do animation under cocos2d 2.0 you need to create sprite frame cache, sprite sheet, animation frames, animation, sprite, action, and start the animation.

Create Sprite Frame Cache

    [[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"role.plist"];

Create Sprite Sheet


    CCSpriteBatchNode *spriteSheet = [CCSpriteBatchNode batchNodeWithFile:@"role.png"];

    [self addChild:spriteSheet];

Create Animation Frames


    NSMutableArray *danceAnimationFrames = [NSMutableArray array];
    for(int i=1; i <= 14; i++) {
        [danceAnimationFrames addObject:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:[NSString stringWithFormat:@"role%02d.png", i]]];
    }

Create Animation


    CCAnimation *danceAnimation = [CCAnimation animationWithSpriteFrames:danceAnimationFrames delay:0.1f];

Add Animation to Animation Cache

    [[CCAnimationCache sharedAnimationCache] addAnimation:danceAnimation name:@"danceAnimation"];

Get Animation from Animation Cache

    danceAnimation = [[CCAnimationCache sharedAnimationCache] animationByName:@"danceAnimation"];

Create Sprite


    self.role = [mySprite spriteWithSpriteFrameName:@"role01.png"];

Create Action



    self.danceAction = [CCRepeatForever actionWithAction:[CCAnimate actionWithAnimation:danceAnimation]];

Sample Code for AniEgg.h


#import "cocos2d.h"

#import "mySprite.h"



@interface AniEgg : CCLayer {

    mySprite *_role;
    CCAction *_danceAction;
}

+(CCScene *)scene;
@property (nonatomic, retain) mySprite *role;
@property (nonatomic, retain) CCAction *danceAction;

@end

Sample Code for AniEgg.m


#import "AniEgg.h"



BOOL paused;

int pausedCount;


@implementation AniEgg

@synthesize role = _role;
@synthesize danceAction = _danceAction;


+(CCScene *) scene {
    // 'scene' is an autorelease object.
    CCScene *scene = [CCScene node];
    // 'layer' is an autorelease object.
    AniEgg *layer = [AniEgg node];
    // add layer as a child to scene
    [scene addChild: layer];
    // return the scene
    return scene;
}

-(id) init {
    if( (self=[super init]) ) {
        [[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"role.plist"];
        CCSpriteBatchNode *spriteSheet = [CCSpriteBatchNode batchNodeWithFile:@"role.png"];
        [self addChild:spriteSheet];
        NSMutableArray *danceAnimationFrames = [NSMutableArray array];
        for(int i=1; i <= 14; i++) {
            [danceAnimationFrames addObject:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:[NSString stringWithFormat:@"role%02d.png", i]]];
        }
        CCAnimation *danceAnimation = [CCAnimation animationWithSpriteFrames:danceAnimationFrames delay:0.1f];
        CGSize winSize = [[CCDirector sharedDirector] winSize];
        self.role = [mySprite spriteWithSpriteFrameName:@"role01.png"];
        _role.position = ccp(winSize.width / 2, winSize.height / 2);
        self.danceAction = [CCRepeatForever actionWithAction:[CCAnimate actionWithAnimation:danceAnimation]];
        [spriteSheet addChild:_role];
        [_role runAction:_danceAction];
        paused = NO;
        [self schedule:@selector(nextFrame:) interval:0.1f];
        self.isTouchEnabled = YES;
    }
    return self;
}

- (void) nextFrame:(ccTime)dt {
    if ([_role isTouched]) {
        if (paused) {
            paused = NO;
            [[[CCDirector sharedDirector] actionManager] resumeTarget:_role];
            pausedCount = 0;
        } else {
            paused = YES;
            [[[CCDirector sharedDirector] actionManager] pauseTarget:_role];
            pausedCount = 0;
        }
        [_role setUnTouched];
    }
    if (paused) {
        pausedCount++;
        if (pausedCount >= 20) {
            paused = NO;
            [[[CCDirector sharedDirector] actionManager] resumeTarget:_role];
            pausedCount = 0;            
        }
    }
}

- (void) dealloc
{
    self.role = nil;
    self.danceAction = nil;
}

@end

2012年6月19日 星期二

Cocos2d 2.0 Ease Actions


Ease actions are special composition actions that alter the time of the inner action. In the Flash world they are often called Tweening or Easing actions.

These actions modify the speed of the inner action, but they don't modify the total running time. If the inner action lasts for 2 seconds, then the total will still be 2 seconds.

The Ease actions alter the linearity of the time. The original inner actions with constant speed looks like:

The inner actions includes: move, rotate, scale, jump, etc.

Ease actions can accelerate or decelerate the inner action.


Ease actions can be classified in 3 types:
  • In actions: The acceleration is at the beginning of the action
  • Out actions: The acceleration is at the end of the action
  • InOut actions: The acceleration is at the beginning and at the end.

Ease

  • CCEaseIn
     
          Acceleration at the beginning.

          example:
      id move = [CCMoveTo actionWithDuration:2 position:location];
      id ease = [CCEaseIn actionWithAction:move rate:3];
      [mySprite runAction:ease];

  • CCEaseOut

      
          acceleration at the end.



          example:
      id move = [CCMoveTo actionWithDuration:2 position:location];
      id ease = [CCEaseOut actionWithAction:move rate:3];
      [mySprite runAction:ease];

  • CCEaseInOut

      
          Acceleration at the beginning/end.



          example:
      id move = [CCMoveTo actionWithDuration:2 position:location];
      id ease = [CCEaseInOut actionWithAction:move rate:3];       [mySprite runAction:ease];

EaseExponential

  • CCEaseExponentialIn

      
          Acceleration at the beginning with Exponential Curve.


          example:
      id move = [CCMoveTo actionWithDuration:2 position:location];
      id ease = [CCEaseExponentialIn actionWithAction:move];
      [mySprite runAction:ease];

  • CCEaseExponentialOut
      
          Acceleration at the end with Exponential Curve.

          example:
      id move = [CCMoveTo actionWithDuration:2 position:location];
      id ease = [CCEaseExponentialOut actionWithAction:move];
      [mySprite runAction:ease];

  • CCEaseExponentialInOut
      
          Acceleration at the beginning/end with Exponential Curve.

          example:
      id move = [CCMoveTo actionWithDuration:2 position:location];
      id ease = [CCEaseExponentialInOut actionWithAction:move];
      [mySprite runAction:ease];

EaseSine

  • CCEaseSineIn
      
          Acceleration at the beginning with Sine Curve.


          example:
      id move = [CCMoveTo actionWithDuration:2 position:location];
      id ease = [CCEaseSineIn actionWithAction:move];
      [mySprite runAction:ease];

  • CCEaseSineOut

      
          Acceleration at the end with Sine Curve.


          example:
      id move = [CCMoveTo actionWithDuration:2 position:location];
      id ease = [CCEaseSineOut actionWithAction:move];
      [mySprite runAction:ease];

  • CCEaseSineInOut

      

          Acceleration at the beginning/end with Sine Curve.

          example:
      id move = [CCMoveTo actionWithDuration:2 position:location];
      id ease = [CCEaseSineInOut actionWithAction:move];
      [mySprite runAction:ease];

Elastic

  • CCEaseElasticIn
      

          Acceleration at the beginning with Elastic Curve.

          example:
      id move = [CCMoveTo actionWithDuration:2 position:location];
      id ease = [CCEaseElasticIn actionWithAction:move period:0.3f];
      [mySprite runAction:ease];
  • CCEaseElasticOut
      

          Acceleration at the end with Elastic Curve.

          example:
      id move = [CCMoveTo actionWithDuration:2 position:location];
      id ease = [CCEaseElasticOut actionWithAction:move  period:0.45f ];
      [mySprite runAction:ease];
  • CCEaseElasticInOut
      
          Acceleration at the beginning/end with Elastic Curve.

          example:
      id move = [CCMoveTo actionWithDuration:2 position:location];
      id ease = [CCEaseElasticInOut actionWithAction:move  period:0.6f ];
      [mySprite runAction:ease];

Bounce

  • CCEaseBounceIn
      
          Acceleration at the beginning with Bounce Curve.

          example:
      id move = [CCMoveTo actionWithDuration:2 position:location];
      id ease = [CCEaseBouncIn actionWithAction:move];
      [mySprite runAction:ease];
  • CCEaseBounceOut

      
          Acceleration at the end with Bounce Curve.
          example:
      id move = [CCMoveTo actionWithDuration:2 position:location];
      id ease = [CCEaseBouncOut actionWithAction:move];
      [mySprite runAction:ease];
  • CCEaseBounceInOut
      
          Acceleration at the beginning/end with Bounce Curve.

          example:
      id move = [CCMoveTo actionWithDuration:2 position:location];
      id ease = [CCEaseBouncInOut actionWithAction:move];
      [mySprite runAction:ease];

Back

  • CCEaseBackIn
      
          Acceleration at the beginning with Back Curve.

          example:
      id move = [CCMoveTo actionWithDuration:2 position:location];
      id ease = [CCEaseBackIn actionWithAction:move];
      [mySprite runAction:ease];

  • CCEaseBackOut
      
          Acceleration at the end with Back Curve.

          example:
      id move = [CCMoveTo actionWithDuration:2 position:location];
      id ease = [CCEaseBackOut actionWithAction:move];
      [mySprite runAction:ease];
  • CCEaseBackInOut
      
          Acceleration at the beginning/end with Back Curve.

          example:
      id move = [CCMoveTo actionWithDuration:2 position:location];
      id ease = [CCEaseBackInOut actionWithAction:move];
      [mySprite runAction:ease];

2012年6月18日 星期一

Cocos2d 2.0 Multi Touch Detection for CCSprite


In order to detect multi touch for CCSprite in Cocos2d 2.0, you must implement CCStandardTouchDelegate.

Implement CCStandardTouchDelegate

@interface mySprite : CCSprite <CCStandardTouchDelegate>

Add Standard Delegation

[[[CCDirector sharedDirector] touchDispatcher] addStandardDelegate:self priority:0];

Remove Delegation

[[[CCDirector sharedDirector] touchDispatcher] removeDelegate:self];

Detect Touched or Not

-(BOOL)touched:(UITouch *)touch {
    CGPoint touchPoint = [touch locationInView:[touch view]];
    touchPoint = [[CCDirector sharedDirector] convertToGL:touchPoint];
    CGRect rect = [self boundingBox];
    if (CGRectContainsPoint(rect, touchPoint)) {
        return YES;
    } 
    return NO;
}

NSSet *allTouches = [event allTouches];
for (UITouch *touch in allTouches) {
    isTouched = [self touched:touch];
    if (isTouched) {
        // Your actions
    }
}

sample code for mySprite.h

#import "cocos2d.h"



@interface mySprite : CCSprite <CCSyandardTouchDelegate>
@end

sample code for mySprite.c


#import "mySprite.h"


@implementation mySprite
-(void)onEnter {
[[[CCDirector sharedDirector] touchDispatcher] addStandardDelegate:self priority:0];
    [super onEnter];
}


-(void)onExit {
[[[CCDirector sharedDirector] touchDispatcher] removeDelegate:self];
    [super onExit];
}


-(void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    NSSet *allTouches = [event allTouches];
    for (UITouch *touch in allTouches) {
        isTouched = [self touched:touch];
        if (isTouched) {
            id enlarge = [CCScaleTo actionWithDuration:0.5f scale:1.1f];
            id resize = [CCScaleTo actionWithDuration:0.5f scale:1];
            [self runAction:[CCSequence actions:enlarge, resize, nil]];
        }
    }
}


-(BOOL)touched:(UITouch *)touch {
    CGPoint touchPoint = [touch locationInView:[touch view]];
    touchPoint = [[CCDirector sharedDirector] convertToGL:touchPoint];
    CGRect rect = [self boundingBox];
    if (CGRectContainsPoint(rect, touchPoint)) {
        return YES;
    } 
    return NO;
}
@end

Cocos2d 2.0 Single Touch Detection for CCSprite

In order to detect single touch for CCSprite in Cocos2d 2.0, you must implement CCTargetedTouchDelegate.

Implement CCTargetedTouchDelegate

@interface mySprite : CCSprite <CCTargetedTouchDelegate>

Add Target Delegation

[[[CCDirector sharedDirector] touchDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES];

Remove Delegation

[[[CCDirector sharedDirector] touchDispatcher] removeDelegate:self];

Detect Touched or Not

CGPoint touchPoint = [touch locationInView:[touch view]];
touchPoint = [[CCDirector sharedDirector] convertToGL:touchPoint];
CGRect rect = [self boundingBox];
if (CGRectContainsPoint(rect, touchPoint)) {
    return YES;

return NO;

sample code for mySprite.h

#import "cocos2d.h"



@interface mySprite : CCSprite <CCTargetedTouchDelegate>
@end

sample code for mySprite.c


#import "mySprite.h"


@implementation mySprite
-(void)onEnter {
    [[[CCDirector sharedDirector] touchDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES];
    [super onEnter];
}


-(void)onExit {
    [[[CCDirector sharedDirector] touchDispatcher] removeDelegate:self];
    [super onExit];
}


-(BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
    BOOL isTouched = [self touched:touch];
    if (isTouched) {
        [self stopAllActions];
        id enlarge = [CCScaleTo actionWithDuration:0.5f scale:1.1f];
        id resize = [CCScaleTo actionWithDuration:0.5f scale:1];
        [self runAction:[CCSequence actions:enlarge, resize, nil]];
    }
    return isTouched;
}


-(BOOL)touched:(UITouch *)touch {
    CGPoint touchPoint = [touch locationInView:[touch view]];
    touchPoint = [[CCDirector sharedDirector] convertToGL:touchPoint];
    CGRect rect = [self boundingBox];
    if (CGRectContainsPoint(rect, touchPoint)) {
        return YES;
    } 
    return NO;
}
@end