Rotating Screen with Accelerometer

Hi, I have a platform game that uses the accelerometer to move left and right. I’d like to add a feature were the screen rotates opposite to the accelerometer so that the camera is always in the original position, so the scene doesn’t move with the rotation.

Can anyone help me please?

You’re going to need the Mathf.Atan2() function, which takes cartesian coordinates and gives you a rotation (in radians).

The code in my tilt-to-control game looks like so:

float lateral = Input.acceleration.x;
float vertical = Mathf.Sqrt(
     Input.acceleration.y * Input.acceleration.y +
     Input.acceleration.z * Input.acceleration.z);
float angle = -(Mathf.Atan2 ( lateral, vertical) * 180.0f) / Mathf.PI;

And then angle is used to set the Z rotation on the camera with something like

camTransform.localRotation = Quaternion.Euler( 0, 0, angle);

Of course that assumes your camera is looking down the Z axis.

Note that the above code combines the Y and Z accelerometer axis to consider what is the vertical component, which lets you play in a wider range of possible holding-the-device orientations.

1 Like

Thank’s so much for that, it works. Is there a way that I can make it look more smooth though, as the screen is extremely shaky.

Excellent question, sir! Look into damping it (the value of angle) with an accumulated value.

Essentially you would have a class level member variable that might be called accumulatedAngle.

You would compute angle as above, but you would instead feed accumulatedAngle into the transform for the camera.

In between the calculation of angle and the application of accumulatedAngle, you would do a weighted filter such as this line here:

accumulatedAngle = Mathf.Lerp( accumulatedAngle, angle, 2.5f * Time.deltaTime);

You can try other values for 2.5f, which is the “snappiness” of the filter.

How would I acquire “accumulatedAngle”? Sorry, I’m still a bit of a rookie with scripting, Kurt.

The code above essentially gives you a variable low-pass filter (look that term up) that smooths out the high-frequency jitter that comes in via accelerometer.

“accumulatedAngle” is the variable name I chose for the filter’s one single state cell. It’s about the simplest low-pass filter you can create.