Spritekit rotate a node while touching

2019-09-07 06:40发布

问题:

I'm currently working on some sort of top down racer if you will. The idea is to have two buttons, each for turning a car left or right. This all works, but it only works with one touch. I'd like to have the player turn the car by simply holding down the button. I now have

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    /* Called when a touch begins */

    for (UITouch *touch in touches) {
        touched = YES;
        CGPoint location = [touch locationInNode:self];
        SKNode *node = [self nodeAtPoint:location];

        if ([node.name isEqualToString:@"buttonLeft"]) {
            while (touched == YES) {
                playerRotate = player.zRotation;
                playerRotate += playerAngle;
            }
        }
    }
}

-(void)update:(CFTimeInterval)currentTime {
    /* Called before each frame is rendered */
    player.zRotation = playerRotate;
    float dx = playerSpeed * cos(player.zRotation);
    float dy = playerSpeed * sin(player.zRotation);
    player.physicsBody.velocity = CGVectorMake(dx, dy);
}

The velocity of the players car is updated in the update function. And in touchesEnded touched is set to NO. The problem is that this while loop gets stuck (and my phone does not proces any touches anymore), but I know no other way to keep rotating the car as long as the button is pressed. The code works if I remove the while loop. Any help is appreciated!

回答1:

You already have the right idea. Instead of setting your BOOL touched to a generic YES for all touches. Create a touchLeft and touchRight BOOL.

After your if([node.name isEqualToString:@"buttonLeft"]) set the touchLeft BOOL to YES. Create a if([node.name isEqualToString:@"buttonRight"]) and set the touchRight BOOL.

In your update method you can then check for either BOOL YES value and apply code accordingly.

Remember you also need to create the same code logic for touchesEnded in order to set both BOOL back to NO once a touch is no longer present.