Touch Handling in Cocos2D 3.x( 5)
Implement the placement function of new heroes
First, we need a variable to keep the reference of our current mobile hero, so we will add a private instance variable. modify the code in MainScene. m.
Usage:
@implementation MainScene { // this is the section to place private instance variables! CCSprite *currentHero;}
Replace the original code:
@implementation MainScene
Now we have a new private variable. this variable will always hold the reference of our current drag hero, so we can update its position when the screen is moved. let's start assigning the variable in the touchBegan method.
Run the following code:
// create a 'hero' spriteCCSprite *hero = [CCSprite spriteWithImageNamed:@"hero.png"];[self addChild:hero];// place the sprite at the touch locationhero.position = touchLocation;
Replace it with the following code:
// create a 'hero' spritecurrentHero = [CCSprite spriteWithImageNamed:@"hero.png"];[self addChild:currentHero];// place the sprite at the touch locationcurrentHero.position = touchLocation;
Now, the reference of the newly created hero is stored, which allows us to access the newly created hero in the entire object and implement other touch methods.
When a user moves his finger on the screen, we want to move the newly created hero. therefore, we need to implement the touchMoved method, which is called every time the touch changes the position. add this method to MainScene. m:
- (void)touchMoved:(UITouch *)touch withEvent:(UIEvent *)event{ CGPoint touchLocation = [touch locationInNode:self]; currentHero.position = touchLocation;}
What did it do? Every time we touch and move, we get the touch position and move the hero we just created to the new position.
The last step is to reset the reference of the hero when the touch ends or is canceled, because we only want to keep the reference of the currently selected hero. Add the following two methods to MainScene. m:
- (void)touchEnded:(UITouch *)touch withEvent:(UIEvent *)event{ currentHero = nil;}- (void)touchCancelled:(UITouch *)touch withEvent:(UIEvent *)event{ currentHero = nil;}
Now you can build and run your project again. The game behavior should exactly match the algorithm outline, and you should see the following picture:
Doing well! Your next step is to take a closer look at Cocos2d 3.0 for touch processing.