Spyros
Spyros

Reputation: 48626

How to rotate parent SKSpriteNode only and not the child node

I have an SKSpriteNode that has a single child SKSpriteNode. When i rotate the parent node (with SKAction rotateByAngle), the child node is also rotated. I've tried quite a few things (setting child's zRotation to 0, setting allowsRotation=NO, even doing those things in didSimulatePhysics), but the child still rotates with the parent. How can i prevent that?

Upvotes: 4

Views: 1226

Answers (2)

0x141E
0x141E

Reputation: 12753

If the child node's position is (0, 0), you will need to adjust only its rotation. If the child is not at the origin, you will need to adjust its position and rotation to account for the rotation of its parent. Here's an example of how to do that (in Swift):

Calculate and store the angle and radius of the child relative to its parent

    let dx = child.position.x
    let dy = child.position.y

    childAngle = atan2(dy, dx)
    childRadius = sqrt(dx*dx+dy*dy)

Adjust the child's position/rotation to counteract the rotation of the parent. This should be performed after all actions are evaluated.

override func didEvaluateActions() {
    let angle = node.zRotation
    let angleOffset = -angle + childAngle
    let x = childRadius * cos(angleOffset)
    let y = childRadius * sin(angleOffset)
    child.position = CGPointMake(x, y)
    child.zRotation = -angle
}

Upvotes: 0

CodeSmile
CodeSmile

Reputation: 64477

Quite simply:

node.parent.rotation = 90;
node.rotation = -90;

Basically just set the child's rotation to the inverse of the parent's rotation.

Upvotes: 5

Related Questions