1
votes

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);
    }

}

1
what is runLeft and runRight, can you show itKnight0fDragon
Those are just animations of the player running; they change the texture of the character.Exprosul
Well from what I am seeing, you are disabling touch when it is pressed down, so while holding left, right will never registerKnight0fDragon
if I am understanding this, the self.userinteractionEnabled changing is not even needed, you want to keep taking the latest touch, and process its directionKnight0fDragon
Just saw your edit, why are you doing the velocity change like that? Change the velocity inside your touch code, that will eliminate the if statements in your update. (There is no point in setting the same value over and over again)Knight0fDragon

1 Answers

2
votes

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];
}