Swift SpriteKit - Gradually increase rotation

旧时模样 提交于 2019-12-22 18:17:26

问题


I'm experimenting round with @nickfalk's answer on How to rotate sprite in sprite kit with swift on how to rotate a sprite in sprite kit.

How would I adjust this to gradually increase rotation speed up to a maximum, then when the screen is clicked, it gradually slows down and goes in the reverse direction for x amount of time?

Thanks!

Toby.


回答1:


Ok, the following (slightly messy proof of concept) spins a sprite at a constant speed. Upon tap+hold it gradually slows the rotation to a halt. Ending the touch immediately returns the rotation to full speed.

I've set up a scene with the following properties: var sprite : SKSpriteNode? and var shouldDecelerate = false:

The sprite is set up with the preferred details and have a repeactActionForever-action running a 360 degrees rotation. From here its fairly straightforward:

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    shouldDecelerate = true
}

override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
    shouldDecelerate = false
    sprite?.speed = 1
    sprite!.runAction(SKAction.speedTo(sprite!.speed, duration: 1/60))
}

override func update(currentTime: CFTimeInterval) {
    if let sprite = sprite {
        if sprite.speed > 0 && shouldDecelerate {
            let newSpeed = max(sprite.speed - 0.1, 0) // we don't want a negative speed as it will reverse the rotation
            sprite.runAction(SKAction.speedTo(newSpeed, duration: 1/60))
        }
    }
}

If you want a gradual increase in speed you basically just need an if with opposite logic of the one I've included in update() above, oh and you should also remove the sprite?.speed = 1 line in touchesEnded().

If you need to have other move-actions where the speed is not effected by the rotation-speed I suggest you hook the sprite up to an SKNode and let this handle the other actions.



来源:https://stackoverflow.com/questions/30410893/swift-spritekit-gradually-increase-rotation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!