Game Development Reference
In-Depth Information
2.
Add the following code to the beginning of the touchesBegan: method
in ERGScene:
UITouch *touch = [touches anyObject];
SKSpriteNode *touchedNode = (SKSpriteNode *)[self
nodeAtPoint:[touch locationInNode:self]];
if (touchedNode.name == playerName) {
ERGPlayer *player = (ERGPlayer *) touchedNode;
player.selected = YES;
return;
}
On the first line, we get the touch object from the touches set and then try to
find if it intersects any node. To do that, we call the nodeAtPoint: method and
provide the location of the touch by converting touch to the Sprite Kit coordinates
in the locationInNode: method. We want to ignore taps on the background itself,
so this is why we check to make sure the player was tapped.
If we tap the player, we set selected to YES so that the touchesMoved: method
knows that we are dragging the character sprite. After that, we call return to exit
the method, as after this return statement, we have other code that we don't want
to trigger.
The next thing that we need to handle is the touchesMoved: method. We haven't
used that before, so type it as follows:
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
ERGPlayer *player = (ERGPlayer *)[self
childNodeWithName:playerName];
if (player.selected) {
player.position = [touch locationInNode:self];
}
}
This method ( touchesMoved: ) checks if the player is actually selected, and if it
is, the coordinates are changed to the touch location. We only want to drag the
character sprite if touches began on it.
 
Search WWH ::




Custom Search