2017-02-15 93 views
2

当前我遇到iOS平台上的问题。基本上,我在2D环境中加载一个指向东的箭头(上边是北,左边是西边,右边是东边,下边是南边)。我预计它可以在3D环境中指向真正的东方,这样它会自动旋转到正确的方向。我画了一张照片来描述我的情况。 (虚线箭头是我装箭头和实线箭头是我想要的东西,如果我使用核心运动数据)指向SceneKit中的正确方向

enter image description here

现在我做

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)!)) 

     })} 

的片段无法自动使箭头旋转到正确的方向。我的想法是获取设备和北面之间的角度,然后将此角度应用于箭头的方向。但是,我怎样才能将角度添加到四元数?还有什么其他的想法来实现这一点?

+0

实际问题是什么?是否正在更新'parent_arrows [0]',并且更新没有显示? 'parent_arrows [0]'没有更新吗?它是更新和显示,但显示错误的方向? – Grimxn

+0

使问题变得简单,我加载一个3D箭头,并且我希望这个箭头指向方向(例如:东)。我回答了我下面得到的,但似乎万向节锁出来了。 – OtakuFitness

回答

1

This 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)) 
} 

这样做后,箭头将指向开始时的正确方向。但是,它带来了另一个问题,我在另一个thread询问。最终答案是this

+0

这段代码并不完美。当我拿起iPhone时,箭头可以在X和Y轴上旋转。 Z轴旋转消失。 – OtakuFitness

相关问题