A child class of CCNode can also receive touch events.
Say your child class name is MyNode.
It has to implement--
CCTouchOneByOneDelegate methods to receive single-touch events.
CCTouchAllAtOnceDelegate to receives multi-touch events
Note:The layer you are going to add this Touch-Enabled subclass of CCNode,should not swallow touch while registering this layer with touch dispatcher.
Class Interface :
#import <Foundation/Foundation.h>
#import "cocos2d.h"
#import "CCProtocols.h"
@interface MyNode : CCNode <CCTouchOneByOneDelegate,CCTouchDelegate>//Implementing only for single touch events
{
@private CGSize winSize;
}
+(MyNode*) addMyNodeToParentClass:(CCNode*)parent;
Class Implementation:
#import "SettingsMenu.h"
@implementation SettingsMenu
+(MyNode*) addMyNodeToParentClass:(CCNode*)parent;
{
return [[self alloc]initWithParentNode:parent];
}
-(id)initWithParentNode:(CCNode*)parent
{
if(self=[super init])
{
winSize=[CCDirector sharedDirector].winSize;
//Registering MyNode with the TouchDispatcher
[self registerWithTouchDispatcher];
//adding a single sprite to check touch events
CCSprite *sprite=[CCSprite spriteWithFile:@"information.png"];
infoButton.position=ccp(winSize.width/2,winSize.height/2);
[self addChild:infoButton];
//adding this node to the parent node
[parent addChild:self];
}
return self;
}
#pragma function registering with Touch Dispatcher
-(void)registerWithTouchDispatcher
{
[[CCDirector sharedDirector].touchDispatcher addTargetedDelegate:self priority:INT_MIN+1 swallowsTouches:YES];//if any other node needs this touch do not swallow this touch
}
#pragma -CCTouchOneByOne delegate methods
-(BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{
CGPoint touchPoint=[[CCDirector sharedDirector] convertTouchToGL:touch];
if(CGRectContainsPoint(infoButton.boundingBox, touchPoint))
{
printf("\nTouch received on information button");
}
return YES;
}
-(void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event
{
CGPoint movedTouchPoint=[[CCDirector sharedDirector] convertTouchToGL:touch];
//your code to handle touch-movement
}
-(void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event
{
CGPoint touchEndPoint=[[CCDirector sharedDirector] convertTouchToGL:touch];
//your code to handle touch-end
}
-(void)ccTouchCancelled:(UITouch *)touch withEvent:(UIEvent *)event
{
//handle event for incoming SMS,Call ect.
}
#pragma -method to remove Touch Dispatcher
-(void)removeTouchDispatcher
{
[[CCDirector sharedDirector].touchDispatcher removeDelegate:self];
}
If MyNode needs to implement multi-touch events implement CCTouchAllAtOnceDelegate's delegate methods---
////////////////////////////////////////////////////////////////
-(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
{
}