How to use the accelerometer in Android?

Hi everyone,

I’m currently want to add accelerometer support in my game for the movement.

First I call Accelerometer.Initialize();
And access the data with accelerometerState = Accelerometer.GetState();

But this does not work as expected. The three values are always 0 and accelerometerState.IsActive is always false.

Does someone know what I’m doing wrong/I forgot?

Best regards,
Webo

Hi,
here is code from one of my games, it’s old but working - you can take a look. the only issue - on tablets it might mess axis, so you need to consider “native device orientation”

    static Accelerometer _accelSensor;

    static public void Start()
    {
        if (_accelSensor == null)
        {
            _accelSensor = new Accelerometer();
            
            _accelSensor.CurrentValueChanged += _accelSensor_CurrentValueChanged;

             _accelSensor.Start();
            
        }
    }

    static void _accelSensor_CurrentValueChanged(object sender, SensorReadingEventArgs<AccelerometerReading> e)
    {
       
            //need to consider orientation here,if support only landscape might be like this
            if (Settings.IsLandscape)
            {
                GravityDirection.Y = -(float)e.SensorReading.Acceleration.Y*gravityCoeff;
                GravityDirection.X = -(float)e.SensorReading.Acceleration.X * gravityCoeff; 
            }
            else
            {
                GravityDirection.Y = -(float)e.SensorReading.Acceleration.X * gravityCoeff; 
                GravityDirection.X = (float)e.SensorReading.Acceleration.Y * gravityCoeff;
            }
        
    }
    
    
}

Hi All,

The behaviour if the Accelerometer has changed since this post … is anybody around to help?

The issues I faced:

  • I create a new accelerometer: Accelerometer acc = new Accelerometer();
  • acc.Start(); throws an exception saying it is already started (or something similar)
  • acc.Status and acc.CurrentValue.Accelerometer, both are giving back a Vector3(0,0,0)
  • I create an event listener on acc.CurrentValueChanged, but that event is never triggered.

Is there a description somewhere, a user guide, how to use the Monogame Accelerometer for Android properly?

Thanks!

I know this is an old topic now but I’m replying anyway because information on the accelerometer does seem to be a bit sparse, so maybe it’ll help someone else.

I just had a go at using it and it seemed fine. Here’s what I did:

  • Declare Accelerometer acc = new Accelerometer() at the start of the Game1 class automatically generated by Monogame.

  • Put acc.Start() in the Initialize() method.

Done.

Now I just call acc.CurrentValue.Acceleration when needed.