cocos2d-iphonecocosbuilder

Making any given instance of a CCNode reactive to touch


So in my project I am using Cocos2D with CocosBuilder. I have assigned a few of my characters to be subclasses of CCNode with child CCSprites, etc.

I want these CCNodes to be reactive to touch - for example, if I touch any of them, they'd play a context sensitive animation. I only want to know how to make the node reactive to touch (or perhaps, having the layer reactive to touch which detects whether you've touched a sprite or not), the animation part is fine.

Any ideas? that would be lovely.

Sam


Solution

  • Turns out that this is fairly easy. In the header file of your class, you must define the class as implementing the protocol , like so:

    @interface Foo : CCNode <CCTouchOneByOneDelegate>
    {
    
    }
    

    and you must implement onEnter and onExit like this:

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

    and you must implement ccTouchBegan (if you're using the OneByOneDispatcher)