2017-02-15 82 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