Search code examples
iossprite-kitskaction

Will adding the same type of SKAction to a sprite override the previous action?


I have accelerometer updates that I am sampling to get vertical and horizontal rates. I perform this every frame. Then I create a vector and pass it to a moveBy SKAction. However I am not sure if this can overload the system or if everytime I add the new SKAction it stops the previous one, discards it and runs the new one.


Solution

  • Adding an SKAction to a node does not remove any previous actions applied to it. They will be executed simultaneously.

    If you want to remove any previous action on a node before applying a new one, use the following code.

    SKAction *newAction = [SKAction waitForDuration:1.0]; //Sample new action
    
    [node removeAllActions];
    [node runAction: newAction];
    

    If however, you want to remove a specific action (and not all actions):

    //In your accelerometer update method
    SKAction *newAction = [SKAction waitForDuration:1.0]; //Sample new action
    
    [node removeActionForKey:@"waitAction"];
    [node runAction: newAction withKey:@"waitAction"];
    

    I would also suggest to use the physics environment if you want to move the node based on accelerometer updates. This can be done by attaching a SKPhysicsBody to the node and applying a vector calculated on the basis of the accelerometer's status. It will seem more natural and handling collisions and contacts will be simpler.