Reputation: 480
I am trying to rotate one sprite node to another. It rotates but not well. How can I fix it?
I have tried:
let blaster = self.childNode(withName: blaster)
let currentBlasterPosition = blaster!.position
let angle = atan2(currentBlasterPosition.y - cubes[0].position.y, currentBlasterPosition.x - cubes[0].position.x)
let rotateAction = SKAction.rotate(toAngle: angle + 90, duration: 0.0)
blaster!.run(SKAction.sequence([rotateAction]))
The SKSpriteNode
is rotating for about -30 to 30 degrees from the point it should be (depending on its position).
Upvotes: 1
Views: 78
Reputation: 109
Instead of dealing with calculating the angles yourself, use SKConstraint for that task.
Assuming your cubes
is an Array of SKNodes:
let constraint = SKConstraint.orient(to: cubes[0], offset: SKRange(constantValue:0))
blaster!.constraints = [constraint]
You will have to do this just once, instead of every frame. The constraint is automatically applied every frame.
To remove it, set the blaster's constraints back to nil
:
blaster!.constraints = nil
Upvotes: 2