I am making my first game for Windows Phone (XNA). I use the accelerometer to change the position of the crosshair on the screen:

Here is the code in my Initialize () function (note that Accelerometer is a local variable declared only in this function):
Accelerometer accelerometer = new Accelerometer(); accelerometer.CurrentValueChanged += accelerometer_CurrentValueChanged; accelerometer.Start();
And an event handler:
void accelerometer_CurrentValueChanged(object sender, SensorReadingEventArgs<AccelerometerReading> e) { lock (accelerometerVectorLock) { accelerometerVector = new Vector3( (float)e.SensorReading.Acceleration.X, (float)e.SensorReading.Acceleration.Y, (float)e.SensorReading.Acceleration.Z); } }
This works fine on a Windows Phone emulator, but on my Nokia Lumia 520 connected to a computer and launched from Visual Studio, however, when I launch a game on my phone (not connected to a computer), the accelometer_CurrentValueChanged event is fired only once, when the application starts.
My solution was to make the accelerometer a member of the Game class, and then the code in Initialize () as follows:
accelerometer = new Accelerometer(); accelerometer.CurrentValueChanged += accelerometer_CurrentValueChanged; accelerometer.Start();
So my question is: why does this solution work? And why is there a difference between an application running from VS and usually, even on the same device?
source share