以变​​化的度数旋转 SKSpritenode

Rotate SKSpritenode by a changing number of degrees

如何定义 SKAction,然后更新我的节点将旋转的度数?我试图用变量定义它,但是当我更新变量值时,操作不会更新。

var degreesToRotate = 4
var direction = 1

let action = SKAction.rotate(byAngle: CGFloat(degreesToRotate * direction), duration: TimeInterval(2))
            charector.run(SKAction.repeatForever(action))

direction = -1
import SpriteKit
import GameplayKit

//Extensions borrowed from here : 

extension Int {
    var degreesToRadians: Double { return Double(self) * .pi / 180 }
    var radiansToDegrees: Double { return Double(self) * 180 / .pi }
}
extension FloatingPoint {
    var degreesToRadians: Self { return self * .pi / 180 }
    var radiansToDegrees: Self { return self * 180 / .pi }
}

let kActionKey = "rotate"

class GameScene:SKScene {

    let purpleCube = SKSpriteNode(color: .purple, size: CGSize(width: 150, height: 150))
    let yellowCube = SKSpriteNode(color: .yellow, size: CGSize(width: 150, height: 150))

    override func didMove(to view: SKView) {


        addChild(purpleCube)
        purpleCube.position.y = purpleCube.size.height
        purpleCube.name = "purple"


        addChild(yellowCube)
        yellowCube.position.y = -yellowCube.size.height
        yellowCube.name = "yellow"

        let rotate = SKAction.rotate(byAngle: CGFloat(-M_PI * 2.0), duration: 5)
        let loop = SKAction.repeatForever(rotate)
        purpleCube.run(loop, withKey: kActionKey)
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

        super.touchesBegan(touches, with: event)


        if let touch = touches.first {

            let location = touch.location(in: self)

            if let cube = atPoint(location) as? SKSpriteNode {

                if let name = cube.name {

                    switch name {

                    case "purple":

                        if let action = purpleCube.action(forKey: kActionKey){

                            purpleCube.run(action.reversed(), withKey: kActionKey)
                        }


                    case "yellow":

                        if action(forKey: "rotating") == nil{
                           yellowCube.run(SKAction.rotate(byAngle: CGFloat(4.degreesToRadians), duration: 0.1), withKey: kActionKey)
                        }



                    default:
                        break
                    }
                }

            }
        }

    }
}

在这个例子中,有两个节点以两种不同的方式旋转。紫色节点以一定的速度顺时针方向不断旋转。为了实现这一点,我创建了一个将精灵旋转 360 度的动作......那将是一次旋转,将永远重复,因此精灵将永远旋转。

关于黄色节点...每次点击它都会旋转4度。目前你必须等待精灵停止旋转,这样你才能旋转更多。这当然是可选的,我只是想告诉你操作键的用处。

旋转方向

由于在 SpriteKit 中 0 度指定为正 x-axis 且正角度为逆时针方向,因此我将紫色立方体旋转 -360 度,从而顺时针旋转精灵。要了解有关 SpriteKit 坐标系的更多信息,请阅读 this documentation section

弧度与度数

如您所见,我说的是度数,而不是弧度...那是因为很难说,我将精灵旋转了 6.2831853072 弧度 :) 这就是我使用扩展的原因将度数转换为弧度和 vice-versa。你可能经常用到这个,所以我给你加了。