Hey all. I just started looking into the cocos2d library. I’ve heard that it’s an easy library to get into if you’re used to programming in ActionScript and I’ve found that a lot of the concepts are indeed similar.
I started looking through sample projects (the sample games linked here were especially helpful) and I saw that handling of touches usually isn’t done in a CCSprite. Rather, the CCLayer that instantiates CCSprites reacts to a touch event and iterates through the sprites it created to detect which CCSprite was touched (if any).
I want CCSprites to handle whether they’ve been touched themselves, and call up to notify that it’s been touched (if needed). The Paddle class found under /tests/TouchesTest does just this – it handles touches by itself.
So, the question I have is: What’s considered best practice for this? Is it better to have touches handled in a central location and iterate through children to see what’s been touched? Or should each child handle its own touch events? Or does it not matter?
I’d prefer each child handling its own touch events but I’d like to follow best practices on this (if they exist). Thanks!
I think it is a matter of preference but I like to have the sprite detect if it was touched by subclassing CCSprite. I make a getter method in my CCSprite subclass that retrieves the state variable from the subclass and then the main program can act accordingly.
Here is an example header file for my CCSprite subclass “spuButton”:
and here is an example of the .m file:
Hope this helps and Happy coding!
ADDITION of tick method and explanation (for Stephan’s question below):
To check the status of the buttons I have a tick: method that basically fires every frame and checks the status of all my buttons.
I check the status of my buttons by calling a isPressed or isNotPressed function that is part of my spuButton class.
Then I do the same kind of check to see if it has been released and respond accordingly. I do it this way because I want to be able to react to multiple button press combos plus I want to do something when it gets pressed down and then something else when it gets released. I use the ccTouchBegan and ccTouchEnded to change the textures(the sprite image) and to change the state variable accordingly.