【问题标题】:How to lock rotation in z of my camera while rotating the camera by using mobile gyroscope input如何在使用移动陀螺仪输入旋转相机时锁定相机的 z 轴旋转
【发布时间】:2017-01-24 20:49:22
【问题描述】:

我正在使用陀螺仪输入统一旋转相机,因为 我希望玩家环顾 x,y。 然而不知何故,z 中也存在旋转。 如何将 z 旋转保持在 0,同时至少保持我现在拥有的 x 和 y 的平滑旋转?

一直在谷歌搜索,但没有找到任何真正保留 z 为 0。

这是我用于旋转的代码,它附加到相机上。

 private void Start()
{
    _rb = GetComponent<Rigidbody>();
    Input.gyro.enabled = true;
}

 private void Update()
{
    float gyro_In_x = -Input.gyro.rotationRateUnbiased.x;
    float gyro_In_y = -Input.gyro.rotationRateUnbiased.y;

    transform.Rotate(gyro_In_x, gyro_In_y, 0);
}

【问题讨论】:

    标签: c# unity3d mobile


    【解决方案1】:

    我的猜测是问题来自transform.rotation *= Quaternion.Euler(gyro_In_x, gyro_In_y, 0); 行。尝试设置旋转值而不是相乘:

    private void Start()
    {
        _rb = GetComponent<Rigidbody>();
        Input.gyro.enabled = true;
    }
    
    private void Update()
    {
        Vector3 previousEulerAngles = transform.eulerAngles;
        Vector3 gyroInput = -Input.gyro.rotationRateUnbiased; //Not sure about the minus symbol (untested)
    
        Vector3 targetEulerAngles = previousEulerAngles + gyroInput * Time.deltaTime * Mathf.Rad2Deg;
        targetEulerAngles.z = 0.0f;
    
        transform.eulerAngles = targetEulerAngles;
    
        //You should also be able do it in one line if you want:
        //transform.eulerAngles = new Vector3(transform.eulerAngles.x - Input.gyro.rotationRateUnbiased.x * Time.deltaTime * Mathf.Rad2Deg, transform.eulerAngles.y - Input.gyro.rotationRateUnbiased.y * Time.deltaTime * Mathf.Rad2Deg, 0.0f);
    }
    

    希望这会有所帮助,

    【讨论】:

    • 抱歉,刚刚注意到我在更新中使用了错误的代码。减号是基于我稍微遵循本教程:youtube.com/watch?v=8ugE1HQPA9g
    • 好吧,我认为使用Rotate() 也可能会在Z 轴上引入不必要的旋转(可能是错误的):我的解决方案(直接操作Transform.eulerAngles)是否解决了您的问题?
    • 是的,谢谢这个作品!我使用此代码代替它做同样的事情,但对我来说更短更清晰,以防有人想知道。 float gyro_In_x = -Input.gyro.rotationRateUnbiased.x; float gyro_In_y = -Input.gyro.rotationRateUnbiased.y; transform.eulerAngles += new Vector3(gyro_In_x, gyro_In_y, 0.0f);
    • 很高兴它有帮助!请记住,在编程时,预制工具很有用,但您必须了解使用它们时隐含的含义(这里是 Rotate 方法):这就是为什么我总是喜欢使用我确定的东西(比如手动编辑Transform.eulerAngles) 当不确定给定方法如何工作时:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多