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]

沒有留言:

張貼留言