加速度计检测旋转而不是加速度

时间:2016-06-01 23:27:10

标签: android unity3d accelerometer unity5

我正试图让设备加速一致来移动一个物体

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

但是当我在我的设备上运行游戏时,对象会根据设备的方向移动和停止,而不是加速。

我还尝试打印Input.acceleration读数

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

我注意到只有旋转设备时三个数字的值才会改变,它们的值变化总是-1和1.

我知道加速计用于测量加速度,而不是旋转。测量旋转的传感器是陀螺仪。

为什么会这样?如何读取加速度而不是旋转。

1 个答案:

答案 0 :(得分:1)

这些天大多数设备都有陀螺仪,所以试试Input.gyro.userAcceleration

请注意,在大多数Android设备上,陀螺仪默认处于关闭状态,您需要将Input.gyro.enabled设置为true。