Implement the new Hero placement function
First we need a variable to keep a reference to our current moving hero, so we'll add a private instance variable. Modify the code in the MAINSCENE.M.
Use:
@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. The variable will always hold a reference to our current drag-and-drop hero, so we can update its position when the screen touch moves. Let's start assigning the variable in the Touchbegan method.
Put 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 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 English is created and its references are stored. This allows us to access the last created hero throughout the object and to implement other touch methods.
When the user moves the finger on the screen, we want to move the hero that we just created. So we need to implement the Touchmoved method, which is called every time the touch changes position. Add this method to MAINSCENE.M:
- (void)touchMoved:(UITouch *)touch withEvent:(UIEvent *)event{ CGPoint touchLocation = [touch locationInNode:self]; currentHero.position = touchLocation;}
What the hell did it do? Each time the touch moves we get the touch position and move the hero just created to the new location.
Our final step is to reset the hero's reference when the touch ends or is canceled, because we only want to keep a reference to the currently selected hero. Add the following 2 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 behavior of the game should be exactly the same as the algorithm outline, and you should see the following screen:
Good job! Your next step will be to be more careful in controlling touch handling in Cocos2d 3.0.
Touch Handling in Cocos2d 3.x (Fri)