Search code examples
androidaccelerometerunity-game-engine

Accelerometer detects rotation instead of acceleration


I'm trying to get the device acceleration in unity to move an object

public class ExampleClass : MonoBehaviour {
    public float speed = 10.0F;
    void Update() {
        Vector3 dir = Vector3.zero;

        // we assume that device is held parallel to the ground
        // and Home button is in the right hand

        // remap device acceleration axis to game coordinates:
        //  1) XY plane of the device is mapped onto XZ plane
        //  2) rotated 90 degrees around Y axis

        dir.x = -Input.acceleration.y;
        dir.z = Input.acceleration.x;

        // clamp acceleration vector to unit sphere
        if (dir.sqrMagnitude > 1)
            dir.Normalize();

        // Make it move 10 meters per second instead of 10 meters per frame...
        dir *= Time.deltaTime;

        // Move object
        transform.Translate(dir * speed);
    }
}

But when I run the game on my device, the object moves and stops depending on the orientation of the device and not it's acceleration.

I tried also to print Input.acceleration readings

GUI.Button(new Rect(10, 10, 150, 80), Input.acceleration.x + "\n" + Input.acceleration.y + "\n" + Input.acceleration.z);

and I noticed that the three numbers' values change only when I rotate the device, and their value changes is always -1 and 1.

I know that that Accelerometer Is used for measuring acceleration ,not rotation. and the sensor that measures rotation is gyroscope.

Why is this happening? How can I read acceleration instead of rotation.


Solution

  • Most of the devices have gyroscope these days so try Input.gyro.userAcceleration

    Note that on most of the android devices gyroscope is turned off by default and you need to set Input.gyro.enabled to true.