Kashif
Kashif

Reputation: 4632

Swift SpriteKit: Flipping parent sprite randomizes child nodes horizontal alignment

I have a parent SKSpriteNode which contains a number of child SKShapeNodes, SKSpriteNodes and SKLabelNodes arranged in specific X,Y position relative to the parent.

When I flip the parent by running an SKAction on it:

SKAction.scaleXTo(-1, duration: duration)

It flips the parent including the children (which I want) but the horizontal alignment of all the children nodes is randomized.

I must mention that I have

parent.anchorPoint = CGPoint(x: 0,y: 0)

Upvotes: 0

Views: 166

Answers (2)

Knight0fDragon
Knight0fDragon

Reputation: 16837

The reason this is happening is because of your anchor point. Scaling (And all transformations) happens on this point. To test, take a piece of paper, put a pencil on the top left corner, then try moving the right side over to the left. leaving the pencil where it is. You will notice that the right side is now -width of the paper

What you need to do in this case, is add the width back in to keep the paper at the same location.

Same rule with the sprites. You have to add the width in when doing a negative scale, then remove the width when going back to a positive scale

(or just put your anchor in the center)

Upvotes: 1

Luca Angeletti
Luca Angeletti

Reputation: 59516

Geometrical transformation you apply to a node are automatically applied to its descendants.

This is why when you move/rotate/scale a node the children (and the grandchildren...) are updated as well.

If you want apply a transformation to your sprite without involving other nodes simply change the structure of you scene moving the children of your sprite like shown below.

As it is now

In this image the green circle is your sprite. In the left scenario when you change the green node, it's children are updated accordingly. And you don't want that.

As it should be

So move to the right scenario. Create a new SKNode (the orange one) and place it as shown below. Now the green node has no children so you can apply geometrical transformation to it without any side effect.

enter image description here

Upvotes: 0

Related Questions