How to make a node to rotate around a point outside of the node in a spritekit game project

2.3k views Asked by At

I came across this answer, but the answer is not clear to me. Can someone provide some sample code?

Create an SKNode and set its position to the center of rotation. Add the node that should rotate around that center as child to the center node. Set the child node's position to the desired offset (ie radius, say x + 100). Change the rotation property of the center node to make the child node(s) rotate around the center point.

Specifically, "Change the rotation property of the center node" to what?

var centerNode: SKSpriteNode = SKSpriteNode(imageNamed: "image1")
centerNode.position = CGPointMake(self.frame.width/2, self.frame.height/2)
self.addChild(centerNode)

var nodeRotateMe: SKSpriteNode = SKSpriteNode(imageNamged: "image2")
nodeRotateMe.position = CGPointMake(self.frame.width/2 + 100, self.frame.height/2 + 100)
centerNode.addChild(nodeRotateMe)

// Change the rotation property of the center node to what??
centerNode.zRotation = ?
1

There are 1 answers

4
justinpawela On BEST ANSWER

You have a couple of options:

1) You could rotate the centerNode over time in your SKScene's update: method by changing its zRotation property manually. You'll have to change the value slowly, at every call to update: to achieve a gradual rotation.

Note that the zRotation property is in radians, with means a 180 degree rotation would be equal to pi (M_PI). SKScene strives to update: at 60 FPS, which means to rotate 360 degrees over 5 seconds, you'd need to increment by 1/300th of a degree every call to update, which would be 1/150th of pi every update.

centerNode.zRotation = centerNode.zRotation + CGFloat(1.0/150.0 * M_PI)

Of course, there is no guarantee that your scene will be able to update at 60 FPS, so you may have to monitor the currentTime variable in update: and adjust accordingly.

2) Probably better, you could use an SKAction to rotate the centerNode for you.

let rotateAction = SKAction.rotateByAngle(CGFloat(2 * M_PI), duration: 5.0)
centerNode.runAction(rotateAction)

Note that the rotation angle is in radians, not degrees. Also note that the centerNode need not be a Sprite Node if you don't want to display an image there; it could be a regular SKNode.