Search code examples
iossprite-kitskactionskspritenode

How do I get a callback from a SpriteKit repeating action when the sprite reaches the end of a path?


I have created my SKAction in this manner:

unicornAction = [SKAction followPath:mypath asOffset:NO orientToPath:YES duration:0.1];

and added it to my SKSprite:

[sprite runAction:[SKAction repeatActionForever:unicornAction] withKey:@"move"];

I do this so that I can adjust the speed at any time within the sprites motion across the path.

When my sprite gets to the end of the path, I need a callback so that I can remove the sprite. How can I get such a callback?

Also, is there a better way of using SKAction to do what I am trying to do, while allowing me to change the speed anywhere during the actions run?


Solution

  • You can use a sequence with a runBlock or performSelector at the end:

    SKAction* sequence = [SKAction sequence:@[unicornAction, [SKAction runBlock:^{
        // code at end of path goes here...
    }]];
    

    You can also use

    [sprite runAction:sequence withKey:@"follow path"];
    

    and later get the action by key:

    SKAction* sequence = [sprite actionForKey:@"follow path"];