简体   繁体   中英

How to lock rotation in z of my camera while rotating the camera by using mobile gyroscope input

I am rotating the camera in unity using gyroscope input, because I want the player to look around the x,y. However somehow there is also rotation in z. How do I keep the z rotation at 0, while at least remaining the smooth rotation in x and y I have now?

Have been googling but haven't found any solutions which actually keep the z at 0.

Here is the code I use for rotation, it's attached to the camera.

 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);
}

My guess is the problem comes from the transform.rotation *= Quaternion.Euler(gyro_In_x, gyro_In_y, 0); line. Trying setting the rotation value instead of multiplying it:

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);
}

Hope this helps,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM