Question

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?

Was it helpful?

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

OTHER TIPS

SKLabelNode does not inherit from UIView and this is not the way to handle animations in SpriteKit. Rather, you should handle this by creating an SKAction and applying it to the node:

SKLabelNode *label = [SKLabelNode labelNodeWithFontNamed:@"Avenir"];
label.position = CGPointMake(30, 200);
label.text = @"Lorem Ipsum";
[self addChild:label];

SKAction *moveLabel = [SKAction moveByX:100 y:0 duration:2.0];
[label runAction:moveLabel];

Not the same coordinates as in your code, but I'm sure you can take it from here. There is also a moveTo: action if that suits your requirements better.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top