Touch Handling in Cocos2D 3.x( 2)
Accept touch
In Cocos2d 3.0, each CCNode and each CCNode subclass can receive and touch. you only need to enable one option. let's complete it in the Custom initiator. replace MainScene. code of the init method in m:
-(Id) init {if (self = [super init]) {// activate touches on this scene self. userInteractionEnabled = TRUE;} return self ;}
Now Cocos2d will know that we want to process the touch in this scenario
Processing touch
Cocos2d will notify us of four different touch events:
When the touch starts, when the touch moves, when the touch ends, when the touch is canceled
These different methods allow you to track the touch on the screen. For our first example, we only need to be notified of the Start event of the touch.
Add the following code to MainScene. m:
-(Void) touchBegan :( UITouch *) touch withEvent :( UIEvent *) event {CCLOG (@ "Received a touch ");}
When you enable a Node interaction, all implemented touch processing methods will be called. now we have implemented the touchBegan method, which will be called at any time when a touch starts. when a touch occurs, we use CCLOG to print debugging information to the console.
Run the app now. Every time you touch the screen, a "Received a touch" message will be displayed on the console. now you know how to receive the touch of any node in your game-this will be very powerful.