简体   繁体   中英

Spritekit Joystick

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.

It sounds like you keep calling your animation over and over again. This would prevent the animation from actually playing past the first couple of frames.

Create a BOOL which you would set the first time the animation runs. Subsequent calls to the animation would check the BOOL's status and determine if the animation is already running. You can reset the BOOL once the joystick is no longer pointing right.


Create a BOOL property:

@property (nonatomic) BOOL animationRunning;

When your joystick values indicate you want your player to run right you call the animation method:

[self runRightAnimation];

Before the animation is run, the BOOL is checked to see if it is already running:

-(void)runRightAnimation {

    if(animationRunning == NO) {

        animationRunning = YES;

        // your animation code...
    }
}

Remember to set your animationRunning = NO; and stop the animation when the joystick is no longer in the desired position.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM