Swift SpriteKit - Gradually increase rotation

核能气质少年 提交于 2019-12-06 08:25:40
T. Benjamin Larsen

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.

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