Touch Handling in Cocos2D 3.x( 3)
Get touch position
The most interesting part is the position of the touch. next we will use the touch position to add the genie to the screen position each time the player clicks. to complete this function, we need to modify the touchBegan implementation. Replace the Old Code as follows:
-(Void) touchBegan :( UITouch *) touch withEvent :( UIEvent *) event {// we want to know the location of our touch in this scene CGPoint touchLocation = [touch locationInNode: self]; // create a 'Hero' sprite CCSprite * hero = [CCSprite spriteWithImageNamed: @ "hero.png"]; [self addChild: hero]; // place the sprite at the touch location hero. position = touchLocation ;}
This implementation is straightforward. the most interesting part is getting the actual Touch Location. the locationInNode method converts the touch OpenGL View coordinates to the coordinates transmitted to the Node of the method as a parameter. (In this example, we need to know the actual position of the screen touch in MainScene ).
Images are part of the starter project you downloaded at the beginning.
Once you run the project, you should be able to fill the screen with MGWU heroes.
Now that you are very familiar with the basics, we will further observe the touch lifecycle and how you create complex touch processing in your game.