Saturday, March 26, 2011

Cocos2d - How to pass touch event to sprite in a layer (CCTouchDispatcher in CCLayer and CCSprite)

I have created a layer which is a subclass of CCLayer. I also have a sprite inside the layer using the subclass of CCSprite. Now the question is that when the layer receives the user's touch event, I want it to do some process and also pass the event to the sprite if the touch location is inside the sprite. That way, in the container level(CCLayer), I can do certain things(ex. show another sprite, start a transition to another scene, ...etc) while the sprite can do some additional works(ex. show an animation, hide itself, ...etc) if it's rectangle is touched by the user.

I have tried several ways and search solutions for a while. Finally I figure it out the right fix for this issue. The key is to make sure the container(CCLayer) does not swallow all the touch events(so sprites inside of it can still receive the touch event if itself is touched). Priority does not seem to matter. However, I still make sure that the parent has lower priority than its children.

Here is the code and diagram showing the correct solution. The subclass of CCSprite will be able to receive touch events via the following three delegate methods by setting the right CCTouchDispatcher parameters.

- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
- (void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event
- (void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event

Relationship between CCLayer and CCSprite and their configurations.


If there are more than one sprite, and all of them need to check if they are touched or not, then make sure you change the swallowsTouches parameter to be "NO". So after the first child of the CCLayer receives the touch event, it will continue to pass to other children(sprites).

0 comments:

Post a Comment