0
votes

I'm trying to execute some animations of my player sprite whenever I change the direction of the joystick.

I'm using TheSneakyNarwhal's drop in Joystick class which uses the following methods:

if (joystick.velocity.x > 0)
{
    [self walkRightAnim];
}
else if (joystick.x < 0)
{
    [self walkLeftAnim];
}
if (joystick.velocity.y > 0)
{
    [self walkUpAnim];
}
else if (joystick.velocity.y < 0)
{
    [self walkDownAnim];
}
if (joystick.velocity.x == 0 && joystick.velocity.y == 0)
{
    [self idleAnim];
}

My [self walkRightAnim];

- (void)walkRightAnim {

    NSLog(@"%f", self.joystick.velocity.x);

    SKTexture *run0 = [SKTexture textureWithImageNamed:@"right1.png"];
    SKTexture *run1 = [SKTexture textureWithImageNamed:@"right2.png"];
    SKTexture *run2 = [SKTexture textureWithImageNamed:@"right3.png"];
    SKAction *spin = [SKAction animateWithTextures:@[run0,run1,run2] timePerFrame:0.2 resize:YES restore:YES];
    SKAction *runForever = [SKAction repeatActionForever:run];
    [self.player runAction:runForever];
}

However, whenever the velocity.x of the joystick is above 0 (moving right) it keeps calling the method from the beginning and won't actually play the full animation.

Only when I stop using the joystick does it play the whole animation.

1

1 Answers

0
votes

You need to start and loop the animation when the joystick velocity changes, rather than every time the joystick velocity is some value. Right now you're triggering the animation action every frame when the joystick is active.

You need to find some way to compare with the previous frame's joystick velocity. For example keep the previous velocity in an ivar, and then do:

if (joystick.velocity.x != previous.velocity.x)
{
    if (joystick.velocity.x > 0)
    {
        [self walkRightAnim];
    }
    else if (joystick.velocity.x < 0)
    {
        [self walkLeftAnim];
    }
}

And so on. Note that this only works if this is a digital joystick, for analog joysticks comparing equality isn't enough.