在 SceneKit iOS 中使用平移手势旋转节点

pra*_*bhu 5 rotation matrix-multiplication ios scenekit swift

我正在使用以下代码使用平移手势旋转节点。我喜欢只在 y 轴上旋转我的节点。

let translation = gestureRecognize.translation(in: gestureRecognize.view!)

let x = Float(translation.x)
let y = Float(-translation.y)
let anglePan = (sqrt(pow(x,2)+pow(y,2)))*(Float)(Double.pi)/180.0

var rotationVector = SCNVector4()
rotationVector.x = 0.0
rotationVector.y = x
rotationVector.z = 0.0
rotationVector.w = anglePan


node.rotation = rotationVector

if(gestureRecognize.state == UIGestureRecognizerState.ended) {
    let currentPivot = node.pivot
    let changePivot = SCNMatrix4Invert( node.transform)

    node.pivot = SCNMatrix4Mult(changePivot, currentPivot)
    node.transform = SCNMatrix4Identity

}
Run Code Online (Sandbox Code Playgroud)

这适用于 Euler 设置为 (x: 0, y: 0, z: 0) 的节点。但是我的节点有 Euler (x: -90, y: 0, z: 0)。对于我的欧拉值,上面的代码以错误的角度旋转对象。如何使用我的/不同的 Euler 值旋转节点?

Bla*_*orz 5

我认为你可能把你需要在这里做的事情变得过于复杂。

在我的示例中,我创建了一个SCNNode带有SCNBoxGeometry 的对象,并Euler Angles按照您的示例进行设置:(x: -90, y: 0, z: 0)。

您需要做的第一件事是创建一个变量来存储围绕 YAxis 的旋转角度:

var currentAngleY: Float = 0.0
Run Code Online (Sandbox Code Playgroud)

然后尝试此功能以围绕 YAxis 旋转您的节点(顺便说一下,它工作正常):

 /// Rotates An Object On It's YAxis
 ///
 /// - Parameter gesture: UIPanGestureRecognizer
 @objc func rotateObject(_ gesture: UIPanGestureRecognizer) {

        guard let nodeToRotate = currentNode else { return }

        let translation = gesture.translation(in: gesture.view!)
        var newAngleY = (Float)(translation.x)*(Float)(Double.pi)/180.0
        newAngleY += currentAngleY

        nodeToRotate.eulerAngles.y = newAngleY

        if(gesture.state == .ended) { currentAngleY = newAngleY }

        print(nodeToRotate.eulerAngles)
}
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你...