使用CMDeviceMotion获取绝对旋转? [英] Obtain absolute rotation using CMDeviceMotion?
问题描述
我正在使用Sprite Kit构建一个简单的游戏,屏幕不会旋转,但我想知道用户为游戏机制持有手机的角度。
I'm building a simple game with Sprite Kit, the screen doesn't rotate but I want to know the angle the user is holding the phone for a game mechanic.
我想用加速度计(x,y)轻松检索我想得到的值,但我发现这是不可靠的,所以我试图存档更好的结果使用 CMDeviceMotion
。我可以获得相当于 data.acceleration.y
但我无法弄清楚如何获得相当于 data.acceleration.x
。
The values I want to get can be easily retrieved with the accelerometer (x, y) but I have found this to be unreliable so I'm trying to archive better results with CMDeviceMotion
. I could obtain the equivalent to data.acceleration.y
but I can't figure out how to get the equivalent of data.acceleration.x
.
if let data = motionManager.accelerometerData? {
let y = CGFloat(data.acceleration.y)
let x = CGFloat(data.acceleration.x)
}
// Device Motion
if let attitude = motionManager.deviceMotion?.attitude? {
let y = CGFloat(-attitude.pitch * 2 / M_PI) // This matches closely with data.acceleration.y
let x = ??????????
}
如何计算 data.acceleration的等价物.x
使用 CMDeviceMotion
?
推荐答案
这就是我现在正在尝试的。我通过实验得到它,所以我不知道它是否正确,可能有更好的解决方案。
This is what I'm trying now. I got to it through experimentation so I cannot tell if it's correct, probably there is a better solution.
if let attitude = motionManager.deviceMotion?.attitude? {
// Convert pitch and roll to [-1, 1] range
let pitch = CGFloat(-attitude.pitch * 2 / M_PI)
let roll = CGFloat(abs(attitude.roll) > M_PI / 2 ? (2 - abs(attitude.roll) * 2 / M_PI) * (attitude.roll > 0 ? 1 : -1) : attitude.roll * 2 / M_PI)
// Calculate x and y
let y = pitch
let x = roll*(1.0-abs(pitch))
}
这篇关于使用CMDeviceMotion获取绝对旋转?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!