Windows Phone Accelerometer Support in XNA

Signs

There is no native XNA support for the accelerometer in Windows Phone. It seems to have been moved into a different sensors class. I hope it doesn’t stay there. The accelerometer support in the Zune HD is fantastically easy to use and well in keeping with the other inputs.

I’ve written a tiny wrapper class that implements the accelerometer using the new sensor interface, but I really think this should really be put back into XNA, as event driven stuff really doesn’t sit well with the XNA philosophy of polling:

public class AccelerometerState
{
    public Vector3 Acceleration;

    public AccelerometerState()
    {
    }
}

public class Accelerometer
{
    static Accelerometer()
    {
        AccelerometerSensor.Default.ReadingChanged +=
            new EventHandler<AccelerometerReadingAsyncEventArgs>
                     Default_ReadingChanged);
    }

    static AccelerometerState state = new AccelerometerState();

    static void Default_ReadingChanged(object sender,
                                      AccelerometerReadingAsyncEventArgs e)
    {
        state.Acceleration.X = (float)e.Value.Value.X;
        state.Acceleration.Y = (float)e.Value.Value.Y;
        state.Acceleration.Z = (float)e.Value.Value.Z;
    }

    public static AccelerometerState GetState()
    {
        return state;
    }
}

You need to add the Microsoft.Devices.Sensors library to your References to make this work.

While writing this I tried to use keyboard input to simulate the accelerometer, and I found that there is no XNA keyboard support in the emulator, which is fair enough I suppose (although I’d like it really).

It does really weird things in the debugger though, I got all kinds of strange readings if I tried to find out what keys are pressed at a breakpoint when using the immediate mode window.

Of course, I’ve not been able to try this on  a real device (I wish) but if anyone out there does I’d love to know if it works or not.