Search code examples
iosobjective-csprite-kittouchesbegan

Overriding touches in Spritekit


In the game I am working on you can move a character from left to right by touching the left/right sides of the screen. What I'm trying to do is to make it that if you're touching the left side and then touch the right side, the character starts moving right instead of left; the action to move left is overridden. I have currently made it so that the game is single-touch but the method of overriding the previous touch is where I'm stuck at. My code:

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInNode:self];

if (location.x < screenWidth/2){ leftMovement = YES; [player runLeft]; } else { rightMovement = YES; [player runRight]; } self.userInteractionEnabled = NO; } - (void) touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{ [self playerStop]; self.userInteractionEnabled = YES; } - (void) update:(NSTimeInterval)currentTime { if (isTouched && leftMovement){ player.physicsBody.velocity=CGVectorMake(-PLAYERSPEED, player.physicsBody.velocity.dy); } else if (isTouched && rightMovement){ player.physicsBody.velocity=CGVectorMake(PLAYERSPEED, player.physicsBody.velocity.dy); } }


Solution

  • One thing you should consider is to change the value of both leftMovement and rightMovement when the user touches the other side of the screen, otherwise, the right movement in update method will never be invoked.

    if (location.x < screenWidth/2){
        leftMovement = YES;
        rightMovement = NO;
        [player runLeft];
    }
    else {
        rightMovement = YES;
        leftMovement = NO;
        [player runRight];
    }