P.Dane P.Dane - 1 month ago 5
Swift Question

How to make a Sprite node spin when a user taps the screen? Swift 3

The result Im looking to achieve: I have a node that is pretty much a bicycle wheel with spokes. When the user tapes the screen, I would like the wheel to not only bounce, but to spin as well with each tap.

What I have now: The node currently bounces when the user taps the screen, just as it should. However it does not spin.

I am still learning swift, so any help or advice is greatly appreciated.

Code:

wheelNode = SKSpriteNode(imageNamed: "wheel")
wheelNode.zPosition = 1
wheelNode.position = CGPoint(x: self.frame.midX, y: self.frame.midY)
wheelNode.physicsBody = SKPhysicsBody(circleOfRadius: wheelNode.size.width / 0.70)
wheelNode.physicsBody?.isDynamic = true
wheelNode.physicsBody?.allowsRotation = true

self.addChild(wheelNode)

override func touchesBegan(_ _touches: Set<UITouch> , with event: UIEvent?) {
if gameOver == false {

self.wheelNode.physicsBody?.velocity = CGVector(dx: 0, dy: 0)
self.wheelNode.physicsBody?.applyImpulse(CGVector(dx: 5, dy: 25))

}

}

Nik Nik
Answer

To have the SKSpriteNode rotating, add this to touchesBegan:

wheelNode.run(SKAction.repeatForever(SKAction.rotate(byAngle: CGFloat.pi * 2.0, duration: 2)), withKey: "rotateWheel")

To rotate in the opposite direction, change CGFloat.pi to -CGFloat.pi

You can fidget with the duration to change the duration for a complete rotation.

In touchesEnded, to stop the action, call:

removeAction(forKey: "rotateWheel")

This way, the wheels rotation doesn't get affected by the physics world. If you want a different way to do the rotating, take a look at this link (and read the comment from @Knigh0fDragon): http://stackoverflow.com/a/39779986/6728196

The logic would still be the same however. In that you need to start the rotating in touchesBegan then end/stop it in touchesEnded.

Comments