使用 CMDeviceMotion 获得绝对旋转? [英] Obtain absolute rotation using CMDeviceMotion?

查看:26
本文介绍了使用 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 = ??????????
}

如何使用 CMDeviceMotion 计算 data.acceleration.x 的等效值?

How do I calculate the equivalent to data.acceleration.x using 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆