Help with TouchEvent


I have my sprites on screen and I have a vector that stores each sprite.

Can a CCSprite* handle a touch event? Or just the CCLayer*?

What is the best way to decide what sprite was touched? Should I store the coordinates of where the sprite is (in the sprite class) and when I get the event, see if where the user touched is where the sprite is by looking through the vector and getting each sprites current coordinates?

UPDATE: I subclass CCSprite:

class Field : public cocos2d::CCSprite, public cocos2d::CCTargetedTouchDelegate

and I implement functions:

cocos2d::CCRect rect(); virtual void onEnter(); virtual void onExit();
bool containsTouchLocation(cocos2d::CCTouch* touch);
virtual bool ccTouchBegan(cocos2d::CCTouch* touch, cocos2d::CCEvent* event);
virtual void ccTouchMoved(cocos2d::CCTouch* touch, cocos2d::CCEvent* event);
virtual void ccTouchEnded(cocos2d::CCTouch* touch, cocos2d::CCEvent* event);
virtual void touchDelegateRetain();
virtual void touchDelegateRelease();

I put CCLOG statements in each one and I dont hit them!

When I touch the CCLayer this sprite is on though I do hit those in the class that implements the Layer and puts these sprites on the layer.


I would suggest:

  1. Don’t make a touch delegate out of every sprite
  2. Instead use one or two layers to capture touch events (maybe your base layer and HUD layer for example). If it seems more convenient, some of them can be targeted delegates with more urgent priority to catch touches first and then consume the event if the touch hit something.
  3. In the layer’s touch handler, convert the x,y -coordinates to the node space of whatever Layer your sprites are in.
  4. Iterate over sprites and see which one if any was hit (could use sprite:boundingBox():containsPoint(…) for example. Sprites already store information about their location)


Thanks Sami for the advice. Using my Layer works just fine.