Accept Touch
In Cocos2d 3.0 each ccnode and every Ccnode subclass can receive touch. You just have to turn on an option. Let's do it in a custom initializer. Replace the code for the Init method in MAINSCENE.M:
- (id)init{ if (self = [super init]) { // activate touches on this scene self.userInteractionEnabledTRUE; } returnself;}
Now cocos2d will know that we want to handle touch in this scene
Handle Touch
Cocos2d will notify us of 4 different touch events:
- When the touch starts
- When Touch is moving
- When the touch is over
- When the touch is canceled
These different methods allow you to track the touch on the screen, and for our first example we just need to be notified of the event that the touch started.
Add the following code to MAINSCENE.M:
- (void)touchBegan:(UITouch *)touch withEvent:(UIEvent *)event{ CCLOG(@"Received a touch");}
When the user opens a node interaction, all the implemented touch processing methods are called. We have now implemented the Touchbegan method, which will be called at any time when a touch begins. When the touch occurs, we use Cclog to print debug information to the console.
Now run the app, and each time you touch the screen, a "Received a touch" message will be displayed in the console. Now you know how to receive any touch of a node in your game-it will be very powerful feature.
Touch Handling in Cocos2d 3.x (two)