I have a toon (player.physicsbody) which I want to move left and right by pressing two buttons (like a ship in Space Invaders). I have coded this and it works ok, the problem comes when I run the app in a device, if "left button" is pressed, pressing "right button" does nothing and viceversa.
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [[event allTouches] anyObject];
CGPoint location = [touch locationInNode:self];
SKNode *node = [self nodeAtPoint:location];
if ([node.name isEqualToString:@"rightbutton"]){
player.physicsBody.velocity=CGVectorMake(200, player.physicsBody.velocity.dy);
}
if ([node.name isEqualToString:@"leftbutton"]){
player.physicsBody.velocity=CGVectorMake(-200, player.physicsBody.velocity.dy);
}
}
Calling [event allTouches] returns an NSSet of UITouch events. Calling [[event allTouches] anyObject] returns only one member of that set. I modified your code to iterate over all touches in the set.
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
for (UITouch *touch in [event allTouches]) {
CGPoint location = [touch locationInNode:self];
SKNode *node = [self nodeAtPoint:location];
if ([node.name isEqualToString:@"rightbutton"]){
player.physicsBody.velocity=CGVectorMake(200, player.physicsBody.velocity.dy);
}
else if ([node.name isEqualToString:@"leftbutton"]){
player.physicsBody.velocity=CGVectorMake(-200, player.physicsBody.velocity.dy);
}
}
}