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

2012年6月15日 星期五

Cocos2d 2.0 Composite Actions

You may compose your actions using the following actions:
  • Sequence Action - CCSequence
  • Spawn Action - CCSpawn
  • Repeat Action - CCRepeat
  • RepeatForever Action - CCRepeatForever

Composite Actions

Sequence

  • CCSequence
          The CCSequence action is a list of actions. The actions are executed in the order that they are defined.

          example:
      id scale = [CCScaleBy actionWithDuration:0.5 scaleX:1.25f scaleY:0.8f];
      id scale_reverse = [scale reverse];
      [mySprite runAction:[CCSequence actions:scale, scale_reverse, scale_reverse, scale, nil]];

Spawn


  • CCSpawn
          The CCSpawn action lets you run several actions at the same time. The duration of the CCSpawn action will be the duration of the longest sub-action.

          example:
      [mySprite runAction:[CCSpawn actions:
             [CCMoveTo actionWithDuration:4 position:ccp(40, 40)],
             [CCRotateBy actionWithDuration:2 angle:360],
             [CCBlink actionWithDuration:3 blinks:12],
             nil]];

Repeat

  • CCRepeat
          The CCRepeat action lets you repeat an action a limited number of times.

          example:
      id scale = [CCScaleBy actionWithDuration:0.5 scaleX:1.25f scaleY:0.8f];
      id scale_reverse = [scale reverse];
      [mySprite runAction:[CCRepeat actionWithAction:[CCSequence actions:scale, scale_reverse, scale_reverse, scale, nil] times:5]];

RepeatForever

  • CCRepeatForever
          The CCRepeatForever action is a special action. Since it will repeat an action forever, its duration can't be measured.

          example:
      [mySprite runAction:[CCRepeatForever actionWithAction:[CCSequence actions:scale, scale_reverse, scale_reverse, scale, nil]]];

2012年6月14日 星期四

Cocos2d 2.0 Basic Actions

Actions are like orders given to any CCNode object. These actions usually modify some of the object's attributes like positionrotationscale, etc. If these attributes are modified during a period of time, they are CCIntervalAction actions, otherwise they are CCInstantAction actions.

Basic Actions

Basic actions are the ones that modify basic properties like:

Position


  • CCMoveBy

          Moves a CCNode object x,y pixels by modifying it's position attribute. x and y are relative to the position of the object. Duration is is seconds.

          example:
      [mySprite runAction:[CCMoveBy actionWithDuration:1                                     position:ccp(200, 200)]];


  • CCMoveTo

          Moves a CCNode object to the position x,y. x and y are absolute coordinates by modifying it's position attribute.

          example:
      [mySprite runAction:[CCMoveTo actionWithDuration:1 position:ccp(200, 200) ]];

  • CCJumpBy

          Moves a CCNode object simulating a parabolic jump movement by modifying it's position attribute.

          example:
      [mySprite runAction:[CCJumpBy actionWithDuration:1 position:ccp(200, 200)  height:100 jumps:5]];


  • CCJumpTo
          Moves a CCNode object to a parabolic position simulating a jump movement by modifying it's position attribute.

          example:
      [mySprite runAction:[CCJumpTo actionWithDuration:1 position:ccp(200, 200)  height:80 jumps:5]];


  • CCBezierBy


          An action that moves the target with a cubic Bezier curve by a certain distance.

          example:
      ccBezierConfig bezier;
      bezier.controlPoint_1 = ccp(0, 100);
      bezier.controlPoint_2 = ccp(100, 100);
      bezier.endPosition = ccp(200,200);
      [mySprite runAction:[CCBezierBy actionWithDuration:1 bezier:bezier]];

  • CCBezierTo

          An action that moves the target with a cubic Bezier curve to a destination point.

          example:
      ccBezierConfig bezier;      bezier.controlPoint_1 = ccp(0, 100);
      bezier.controlPoint_2 = ccp(100, 100);
      bezier.endPosition = ccp(200,200);
      [mySprite runAction:[CCBezierTo actionWithDuration:1 bezier:bezier]];

  • CCPlace

          Places the node in a certain position.

          example:
      [mySprite runAction:[CCPlace actionWithPosition:ccp(200, 200)]];

Scale

  • CCScaleBy

          Scales a CCNode object a zoom factor by modifying it's scale attribute.

          example:
      [mySprite runAction:[CCScaleBy actionWithDuration:1 scaleX:2.0f scaleY:0.5f]];

  • CCScaleTo

          Scales a CCNode object to a zoom factor by modifying it's scale attribute.

          example:
      [mySprite runAction:[CCScaleTo actionWithDuration:1 scaleX:0.5f scaleY:2.0f]];


Rotation


  • CCRotateBy


          Rotates a CCNode object clockwise a number of degrees by modiying it's rotation attribute.

          example:
      [mySprite runAction:[CCRotateBy actionWithDuration:1 angle:60]];



  • CCRotateTo

          Rotates a CCNode object to a certain angle by modifying it's rotation attribute. The direction will be decided by the shortest angle.

          example:
      [mySprite runAction:[CCRotateTo actionWithDuration:1 angle:90]];


Visibility


  • CCShow

          Show the node.

          example:
      [mySprite runAction:[CCShow action]];

  • CCHide

          Hide the node.

          example:
      [mySprite runAction:[CCHide action]];

  • CCBlink

          Blinks a CCNode object by modifying it's visible attribute.

          example:
      [mySprite runAction:[CCBlink actionWithDuration:4 blinks:8]];

  • CCToggleVisibility
          Toggles the visibility of a node.

          example:
      [mySprite runAction:[CCToggleVisibility action]];

Opacity

  • CCFadeIn
          Fades In an object that implements the CCRGBAProtocol protocol. It modifies the opacity from 0 to 255. The "reverse" of this action is FadeOut.

          example:
      [mySprite runAction:[CCFadeIn actionWithDuration:1]];

  • CCFadeOut
          Fades Out an object that implements the CCRGBAProtocol protocol. It modifies the opacity from 255 to 0. The "reverse" of this action is FadeIn.


          example:
      [mySprite runAction:[CCFadeOut actionWithDuration:1]];


  • CCFadeTo

          Fades an object that implements the CCRGBAProtocol protocol. It modifies the opacity from the current value to a custom one.

          example:
      [mySprite runAction:[CCFadeTo actionWithDuration:1 opacity:128]];


Color

  • CCTintBy

          Tints a CCNode that implements the CCNodeRGB protocol from current tint to a custom one.

          example:
      [mySprite runAction:[CCTintBy actionWithDuration:1
                                    red:20
                                    green:30
                                    blue:40]];

  • CCTintTo
          Tints a CCNode that implements the CCNodeRGB protocol from current tint to a custom one.

          example:
      [mySprite runAction:[CCTintTo actionWithDuration:1
                                    red:20
                                    green:130
                                    blue:240]];

2012年6月13日 星期三

Cocos2d 2.0 Touch Input

Cocos2d supports two different ways of handling touch events. These are defined by two different types of delegates: Standard Touch Delegate and Targeted Touch Delegate.

Standard Touch Delegate

Standard Touch Event includes ccTouchesBegan:withEvent:ccTouchesMoved:withEvent:ccTouchesEnded:withEvent:ccTouchesCancelled:withEvent:.

@protocol CCStandardTouchDelegate <NSObject>
@optional
- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)ccTouchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event;
@end


You'll get all events, and all touches; it will be up to you to sort out which touches you care about in a multi-touch environment.


To get these events in a CCLayer subclass, you simply set isTouchEnabled = YES:


self.isTouchEnabled = YES;

Targeted Touch Delegate

Targeted Touch Event includes ccTouchBegan:withEvent:ccTouchMoved:withEvent:ccTouchEnded:withEvent:ccTouchCancelled:withEvent:.


@protocol CCTargetedTouchDelegate <NSObject>

- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event;

@optional
- (void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event;
- (void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event;
- (void)ccTouchCancelled:(UITouch *)touch withEvent:(UIEvent *)event;
@end

Targeted Touch methods provide only a single touch.  Standard Touch methods provide a set of touches.

The ccTouchBegan method is required and returns a boolean value. So ccTouchBegan will be invoked separately for each of the available touches, and you return YES to indicate a touch you care about. Only touches claimed by ccTouchBegan will be subsequently passed on to the Moved, Ended, and Cancelled events.

To receive these events, you must register as a targeted touch delegate with the global dispatcher. In a CCLayer subclass, override registerWithTouchDispatcher as follows:

-(void) registerWithTouchDispatcher
{
    [[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self
                                          priority:0 swallowsTouches:YES];
}

Multi Touch

To recieve multi-touch events, you have to activate them. You can do this by adding the following code in your AppDelegate's applicationDidFinishLaunching:

[glView setMultipleTouchEnabled:YES];

If you are using Cocos2d with Storyboard, you can do this by adding the following code in your ViewController's viewDidLoad:

[self.view setMultipleTouchEnabled:YES]

Cocos2d 2.0 Basic Concepts

There are some basic concepts introduced in Cocos2d that you will need to know when developing a cocos2d application.
  • Scenes
  • Director
  • Layers
  • Sprites

Scenes

A scene is more or less an independent piece of the app workflow. Your app can have many scenes, but only one of them is active at a given time.
Sample Workflow using Scenes
A cocos2d CCScene is composed of one or more layers (CCLayer), all of them piled up. Layers give the scene an appearance and behavior; the normal use case is to just make instances of Scene with the layers that you want.

There is also a family of CCScene classes called transitions (CCTransitionScene) which allow you to make transitions between two scenes.


Since scenes are subclasses of CCNode, they can be transformed manually or by using actions.

Director

The CCDirector is the component which takes care of going back and forth between scenes. 

The CCDirector is a shared (singleton) object. It knows which scene is currently active, and it handles a stack of scenes. The CCDirector is the one who will actually change the CCScene, after a CCLayer has asked for push, replacement or end of the current scene.

Layers

CCLayer has a size of the whole drawable area, and knows how to draw itself. It can be semi transparent, allowing to see other layers behind it. Layers are the ones defining appearance and behavior, so most of your programming time will be spent coding CCLayer subclasses that do what you need. 


The CCLayer is where you define event handlers. Events are propagated to layers until some layer catches the event and accepts it.


Cocos2d provides a library of useful predefined layers such as CCMenu, CCColorLayer, CCMultiplexLayer.


Layers can contain CCSprite objects, CCLabel objects and even other CCLayer objects as children.


Since layers are subclass of CCNode, they can be transformed manually or by using actions.

Sprites

A cocos2d' sprite is like any other computer sprite. It is a 2D image that can be moved, rotated, scaled, animated, etc.

Sprites (CCSprite) can have other sprites as children. When a parent is transformed, all its children are transformed as well.

Since sprites are subclass of CCNode, they can be transformed manually or by using actions.

Cocos2d 2.0 Menu Item

Menus

Menus provide one way for users to interact with your game using a familiar GUI concept, “buttons.

Menu Item to choose from:

  • CCMenuItemAtlasFont
  • CCMenuItemFont
  • CCMenuItemImage
  • CCMenuItemLabel
  • CCMenuItemSprite
  • CCMenuItemToggle

Create Menu Item

CCMenuItemImage *menuItemNormal = 
                     [CCMenuItemImage           
                         itemWithNormalImage:@"normal.png"
                         selectedImage:@"normal_selected.png"
                         block:^(id sender) {
                             [[CCDirector sharedDirector] replaceScene:[NormalScene scene]];
                         }];

CCMenuItemImage *menuItemSlim = 
                     [CCMenuItemImage 
                         itemWithNormalImage:@"slim.png"
                         selectedImage:@"slim_selected.png"
                         block:^(id sender) {
                             [[CCDirector sharedDirector] replaceScene:[SlimScene scene]];
                         }];

    CCMenuItemImage *menuItemFat = 
                         [CCMenuItemImage
                             itemWithNormalImage:@"fat.png"
                             selectedImage:@"fat_selected.png"
                             block:^(id sender) {
                                 [[CCDirector sharedDirector] replaceScene:[FatScene scene]];
                             }];

    Create Menu and add Menu Items

    CCMenu *myMenu = [CCMenu menuWithItems:menuItemNormal, 
                                           menuItemSlim, 
                                           menuItemFat, 
                                           nil];

    Add Menu to Scene

    [self addChild:myMenu];