在 SceneKit 中指向正确的方向

Pointing to right direction in SceneKit

目前我在iOS平台上遇到一个问题。基本上,我在 2D 环境中加载一个指向东方的箭头(上方是北,左侧是西,右侧是东,下方是南)。我希望它可以在 3D 环境中指向真实的东方,以便它会自动旋转到正确的方向。我画一张图来准确描述我的情况。 (虚线箭头是我加载的箭头,如果我使用核心运动数据,实线箭头是我想要的)

现在我做到了

let motionManager = CMMotionManager()
    motionManager.deviceMotionUpdateInterval = 1.0 / 60.0
    if motionManager.isDeviceMotionAvailable {
        motionManager.startDeviceMotionUpdates(to: OperationQueue.main, withHandler: { (devMotion, error) -> Void in
                parent_arrows[0].orientation = SCNQuaternion(-CGFloat((motionManager.deviceMotion?.attitude.quaternion.x)!), -CGFloat((motionManager.deviceMotion?.attitude.quaternion.y)!), -CGFloat((motionManager.deviceMotion?.attitude.quaternion.z)!), CGFloat((motionManager.deviceMotion?.attitude.quaternion.w)!))

        })}

该代码段无法自动使箭头向正确的方向旋转。我的想法是获取设备与北方之间的角度,然后将此角度应用于箭头的方向。但是如何将角度添加到四元数呢?有没有其他的想法来实现这个目标?

这个thread启发了我。

 let motionManager = CMMotionManager()
    motionManager.deviceMotionUpdateInterval = 1.0 / 60.0
    if motionManager.isDeviceMotionAvailable {
        motionManager.startDeviceMotionUpdates(to: OperationQueue.main, withHandler: { (devMotion, error) -> Void in
            parent_arrows[0].orientation = self.orient(q: (motionManager.deviceMotion?.attitude.quaternion)!)

        })}
}

func orient(q:CMQuaternion) -> SCNQuaternion{
    let gq1: GLKQuaternion = GLKQuaternionMakeWithAngleAndAxis(GLKMathDegreesToRadians(-heading), 0, 0, 1)
    // add a rotation of the yaw and the heading relative to true north
    let gq2: GLKQuaternion = GLKQuaternionMake(Float(q.x), Float(q.y), Float(q.z), Float(q.w))
    // the current orientation
    let qp: GLKQuaternion = GLKQuaternionMultiply(gq1, gq2)
    // get the "new" orientation
    var rq = CMQuaternion()
    rq.x = Double(qp.x)
    rq.y = Double(qp.y)
    rq.z = Double(qp.z)
    rq.w = Double(qp.w)
    return SCNVector4Make(-Float(rq.x), -Float(rq.y), -Float(rq.z), Float(rq.w))
}

这样做之后,箭头会指向最开始的正确方向。然而,它带来了另一个问题,我在另一个 . The final answer is in this