SKAction to Change AnchorPoint?

989 views Asked by At

I am creating a relatively complicated animation sequence. In it, a certain SKSpriteNode (shark) does two rotations. At the beginning of the animation, it rotates around a certain anchor point ap1, then later rotates around a different anchor point ap2. How should I change anchor points midway through an animation sequence?

Some initial thoughts:

I could change the anchor point outside of SKActions, in the update: loop perhaps.

I could use multiple SKSpriteNodes for the same shark sprite (with their respective anchor points), switching (hiding/showing) the sprite nodes when I need to change the anchor point.

2

There are 2 answers

0
0x141E On

Since changing a sprite's anchor point affects where it's rendered, you will likely need to make some sort of adjustment to prevent the sprite from appearing to suddenly move to a new location. Here's one way to do that:

Create action that changes the anchor point

    SKAction *changeAnchorPoint = [SKAction runBlock:^{
        [self updatePosition:sprite withAnchorPoint:CGPointMake(0, 0)];
    }];

    SKAction *rotate = [SKAction rotateByAngle:2*M_PI duration: 2];

Run action to rotate, change the anchor point, and rotate

    [sprite runAction:[SKAction sequence:@[rotate,changeAnchorPoint,rotate]] completion:^{
        // Restore the anchor point
        [self updatePosition:sprite withAnchorPoint:CGPointMake(0.5, 0.5)];
    }];

This method adjusts a sprite's position to compensate for the anchor point change

- (void) updatePosition:(SKSpriteNode *)node withAnchorPoint:(CGPoint)anchorPoint
{
    CGFloat dx = (anchorPoint.x - node.anchorPoint.x) * node.size.width;
    CGFloat dy = (anchorPoint.y - node.anchorPoint.y) * node.size.height;
    node.position = CGPointMake(node.position.x+dx, node.position.y+dy);
    node.anchorPoint = anchorPoint;
}
0
rizzes On

As Julio Montoya said, the easiest way to do this is to just "translate" code into an SKAction with the method [SKAction runBlock:myBlock].