Problem using LinearAccelerationSensor, Unity

28 Views Asked by At

I'm using Unity. I want to get user device's (mobile phone's) acceleration without gravity. I found this documentation bout new input system, and LinearAccelerationSensor seems like it's what I need but I don't get how to use it.

Here's code I've tried to use:

using UnityEngine;
using UnityEngine.InputSystem;
using TMPro;
 
public class AccelerometerDisplay : MonoBehaviour
{
    public TextMeshProUGUI debugText;
    private LinearAccelerationSensor linearAccelerationSensor;
    Vector3 linearAcceleration;
 
    void Update()
    {
        if (linearAccelerationSensor == null)
        {
            // Attempt to get the LinearAccelerationSensor
            linearAccelerationSensor = InputSystem.GetDevice<LinearAccelerationSensor>();
            if (linearAccelerationSensor != null)
            {
                debugText.text = "Linear Acceleration Sensor found!";
            }
            else
            {
                debugText.text = "Linear Acceleration Sensor not found.";
                return;
            }
        }
 
        linearAcceleration = linearAccelerationSensor.acceleration.ReadValue();
 
        debugText.text = linearAcceleration.x + " " + linearAcceleration.y + " " + linearAcceleration.z ;
    }
}

I tried on both Unity Play and built on my mobile phone and on both it always shows Linear Acceleration Sensor not found.. What I'm doing wrong?

0

There are 0 best solutions below