2012年7月31日 星期二

Cocos2d 2.0 Menu Item Toggle


Set Default Value for Settings

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *soundOnKey = [NSString stringWithString:@"sound_on"];
NSNumber *soundOnValue = [NSNumber numberWithInt:0];
NSDictionary *defaultSoundOnValue = [NSDictionary dictionaryWithObject:soundOnValue forKey:soundOnKey];
[defaults registerDefaults:defaultSoundOnValue];

Declare public variable

CCMenuItem *sound_control_on;
CCMenuItem *sound_control_off;

Create Toggle Item

sound_control_on = [CCMenuItemImage itemWithNormalImage:@"sound_control_on.png" selectedImage:@"sound_control_on_pressed.png" target:nil selector:nil];
sound_control_off = [CCMenuItemImage itemWithNormalImage:@"sound_control_off.png" selectedImage:@"sound_control_off_pressed.png" target:nil selector:nil];
CCMenuItemToggle *sound_control_toggle = [CCMenuItemToggle itemWithTarget:self selector:@selector(sound_control:) items:sound_control_on, sound_control_off, nil];
sound_control_toggle.position = ccp(0, -55);
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *soundOnKey = [NSString stringWithString:@"sound_on"];
[sound_control_toggle setSelectedIndex:[defaults integerForKey:soundOnKey]];

Toggle Handler

-(void) sound_control:(id)sender {
    CCMenuItemToggle *item = (CCMenuItemToggle *)sender;
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *soundOnKey = [NSString stringWithString:@"sound_on"];
    NSNumber *soundOnValue;
    if (item.selectedItem == sound_control_on) {
        soundOnValue = [NSNumber numberWithInt:0];
    } else {
        soundOnValue = [NSNumber numberWithInt:1];
    }
    [defaults setInteger:soundOnValue.intValue forKey:soundOnKey];
}


2012年7月30日 星期一

iOS Preferences and Settings Programming

Set Default Value

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
for (int i = 0; i < 5; i++) {
    NSString *itemKey = [NSString stringWithFormat:@"item%d", i];
    NSNumber *itemValue = [NSNumber numberWithInt:0]; 
    NSDictionary *defaultItem = [NSDictionary dictionaryWithObject:itemValue forKey:itemKey];
    [defaults registerDefaults:defaultItem];
}

Get current value and Increment by one

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
for (int i = 0; i < 5; i++) {
    if (NeedToIncrementByOne[i]) {
        NSString *itemKey = [NSString stringWithFormat:@"item%d", i];
        NSInteger itemValue = [defaults integerForKey:itemKey] + 1;
        [defaults setInteger:itemValue forKey:itemKey];
    }
}

Types Support

setBool:forKey:
setDouble:forKey:
setFloat:forKey:
setInteger:forKey:
setObject:forKey:
setURL:forKey:
setValue:forKey:

Set Nil

setNilValueForKey:


2012年7月9日 星期一

Cocos2d 2.0 Email Sending with Attachment


Implement MFMailComposeViewControllerDelegate

@interface EMailSending : CCLayer <MFMailComposeViewControllerDelegate> {
...
}

-(void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error {
...
}

Add Child View Controller

    emailViewController = [[UIViewController alloc] init];
    [[CCDirector sharedDirector] addChildViewController:emailViewController];

Create Mail Compose View Controller

    MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];

Present Modal View Controller

    [emailViewController presentModalViewController:picker animated:YES];

Dismiss Modal View Controller

    [controller dismissModalViewControllerAnimated:NO];

Create Render Texture and Take Snapshot for this Layer

    CCRenderTexture *renderTexture = [CCRenderTexture renderTextureWithWidth:windowSize.width height:windowSize.height];
    [renderTexture begin];
    [self visit];
    [renderTexture end];
    [renderTexture saveToFile:file format:kCCImageFormatPNG];

Compose EMail with Attachment

    picker.mailComposeDelegate = self;
    [picker setSubject:@"This is test subject"];
    [picker setMessageBody:@"This is test message body" isHTML:YES];
...
    NSString *file = @"screenShot.png";
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *screenShotPath = [documentsDirectory stringByAppendingPathComponent:file];
    NSData *data = [NSData dataWithContentsOfFile:screenShotPath];
    [picker addAttachmentData:data mimeType:@"image/png" fileName:@"attachment .png"];

Save Snapshot to Photo Album

    NSData *data = [NSData dataWithContentsOfFile:screenShotPath];
    UIImage *image = [UIImage imageWithData:data];
    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);

Sample code for EMailSending.h

#import "cocos2d.h"
#import "MessageUI/MessageUI.h"


@interface EMailSending : CCLayer <MFMailComposeViewControllerDelegate> {
    UIViewController *emailViewController;
    CCMenu *menu;
    CCSprite *sprite;
}


+(CCScene *)scene;


@end

Sample code for EMailSending.m

#import "EMailSending.h"

@implementation EMailSending

+(CCScene *)scene {
    CCScene *scene = [CCScene node];
    EMailSending *layer = [EMailSending node];
    [scene addChild:layer];        
    return scene;
}

-(id)init {
    if (self = [super init]) {
        CCMenuItem *emailItem = [CCMenuItemFont itemWithString:@"Email" target:self selector:@selector(emailCallback)];
        menu = [CCMenu menuWithItems:emailItem, nil];
        menu.position = ccp(50, 50);
        [self addChild:menu];
        sprite = [CCSprite spriteWithFile:@"mySprite.png"];
        sprite.position = ccp(200, 200);
        [self addChild:sprite];
        emailViewController = [[UIViewController alloc] init];
        [[CCDirector sharedDirector] addChildViewController:emailViewController];
    }
    return self;
}

-(void)emailCallback {
    [[CCDirector sharedDirector] pause];
    [[CCDirector sharedDirector] stopAnimation];
    MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
    picker.mailComposeDelegate = self;
    [picker setSubject:@"This is test subject"];
    [picker setMessageBody:@"This is test message body" isHTML:YES];
    
    NSString *file = @"screenShot.png";
    [CCDirector sharedDirector].nextDeltaTimeZero = YES;
    CGSize windowSize = [CCDirector sharedDirector].winSize;
    CCRenderTexture *renderTexture = [CCRenderTexture renderTextureWithWidth:windowSize.width height:windowSize.height];
    [renderTexture begin];
    [self visit];
    [renderTexture end];
    [renderTexture saveToFile:file format:kCCImageFormatPNG];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *screenShotPath = [documentsDirectory stringByAppendingPathComponent:file];
    NSData *data = [NSData dataWithContentsOfFile:screenShotPath];
    UIImage *image = [UIImage imageWithData:data];
    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
    [picker addAttachmentData:data mimeType:@"image/png" fileName:@"attachment .png"];

    [emailViewController presentModalViewController:picker animated:YES];
}

-(void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error {
    [[CCDirector sharedDirector] resume];
    [[CCDirector sharedDirector] startAnimation];
    [controller dismissModalViewControllerAnimated:NO];
}
@end

2012年7月5日 星期四

iOS warning

incomplete implementation

To find out which method is not implemented
  • press command+4
  • click the little arrow which describe that the method is not implemented
  • click Method declared here

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