简体   繁体   中英

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))

    }

}

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 @Knight0fDragon): https://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 .

add the following line in the touchesBegan method:

self.wheelNode.physicsBody?.applyAngularImpulse(5)

Than you have a rotation which is consistent to the rest of your physics based game.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM