Search code examples
iosobjective-csprite-kituiviewanimationsklabelnode

Animate an SKLabel in a Scene?


How can I animate the position of an SKLabel in a scene?

I've tried the following but it doesn't seem to be working:

[SKView animateWithDuration:0.3
                                  delay:0.0
                                options:UIViewAnimationOptionCurveEaseOut
                             animations:^{
                                 newBestLabel.position = CGPointMake(CGRectGetMinX(self.frame)+70, CGRectGetMaxY(self.frame)-30);
                             }
                             completion:^(BOOL finished){}];

and

[UIView animateWithDuration:0.3
                                  delay:0.0
                                options:UIViewAnimationOptionCurveEaseOut
                             animations:^{
                                 newBestLabel.position = CGPointMake(CGRectGetMinX(self.frame)+70, CGRectGetMaxY(self.frame)-30);
                             }
                             completion:^(BOOL finished){}];

in viewDidLoad it starts at:

newBestLabel.position = CGPointMake(CGRectGetMinX(self.frame)+70, CGRectGetMaxY(self.frame)+30);

What's wrong here?


Solution

  • Because SKLabelNode is a sub-class of SKNode you can use a method named runAction: and pass in an SKAction that does what you need.

    // create an instance of SKAction
    SKAction *moveLabel = [SKAction moveByX:0.0 y:30.0 duration:1.2];
    
    // tell labelNode to run the action
    [newBestLabel runAction:moveLabel];
    

    It's also worth noting that the coordinate system SpriteKit uses, is different to that of UIKit. Therefor in the above code a positive x value will move to the right and a positive y value will move up!

    There are many methods available to do what you need and a lot more, and are found in SKAction Class Reference