目前我在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)!))
})}
代码段不能自动使箭头旋转到正确的方向。我的想法是得到设备和北方之间的角度,然后将这个角度应用到箭头的方向上。但是如何将角度添加到四元数中呢?还有什么其他的想法来实现这一点吗?
发布于 2017-02-16 09:10:55
这个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中
https://stackoverflow.com/questions/42243907
复制相似问题