0

I use this code to track the movement of the gyroscope and rotate the object:

Vector3 previousEulerAngles = transform.eulerAngles;
Vector3 gyroInput           = -Input.gyro.rotationRateUnbiased;

Vector3 targetEulerAngles   = previousEulerAngles + gyroInput * Time.deltaTime * Mathf.Rad2Deg;
targetEulerAngles.x         = 0.0f;
targetEulerAngles.y         = 0.0f;

transform.eulerAngles       = targetEulerAngles;

Everything works smoothly and almost the way I need, but there are 2 problems. The first is that when the smartphone is sharply rotated and when it is rotated 360 degrees or more, the object begins to roll away from its initial position. A collapse effect appears.

The second problem is that if the device is rotated before starting the application, then the rotation of the object starts from the initial position, and not from the position of the gyroscope. I’ve spent a few days already solving these problems.

Maybe someone has already encountered such a problem?

1 Answer 1

0

For fixing the initial orientation you could once apply Gyroscope.attitude to your objects orientation.

Again if you only want to rotate the object on the Z axis the easiest way would probably be something like e.g.

private void Start()
{
    var attitude = Input.gyro.attitude;
    var targetEulerAngles = attidue.eulerAngles;
    targetEulerAngles.x = 0;
    targetEulerAngles.y = 0;

    transform.eulerAngles = targetEulerAngles;
}

Further the value returned by Gyroscope.rotationRateUnbiased already is a frame-rate independent rotation

in radians per second

so the multiplication by Time.deltaTime is not required / not correct here.

Indeed you could instead of going incremental even just always directly apply the actual current Gyroscope.attitude

private void Update()
{  
    var attitude = Input.gyro.attitude;
    var targetEulerAngles = attidue.eulerAngles;
    targetEulerAngles.x = 0;
    targetEulerAngles.y = 0;

    transform.eulerAngles = targetEulerAngles;
}
Sign up to request clarification or add additional context in comments.

1 Comment

This code works but flips the object 90 degrees when the app starts. I tried to multiply the input by a quaternion, but the angle is not calculated correctly Input.gyro.attitude * Quaternion.Euler(0f, 0f, 90f). In my application, landscape orientation is always enabled. And if I tilt the smartphone slightly forward in this position, then the angle of inclination is still recalculated. Is it possible to track only the rotation along the z-axis, no matter what plane the smartphone is in?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.