Windows Phone 8 Accelerometer Events

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

Position of crosshair

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?

+6
source share
1 answer

Why does this solution work?

This solution works because you keep the link to the accelerometer. Windows Phone applications, like all .NET applications, use an automated memory management system. The background process, called the garbage collector, regularly checks objects, detects those who no longer reference, and cleans them. If you specify the accelerometer as a local variable, it will no longer be called when the function exits, and therefore will be cleared. When you declare him as a member of your class, he will be alive as long as your class lives.

Why is there a difference between an application running from VS and usually on the same device?

When you run the code from Visual Studio, a debugger is included. To help you debug, this affects the way code is executed. Remarkably, this makes the garbage collector less aggressive. This explains why you did not have this problem when testing with an attached debugger. Note that you can achieve the same result by pressing Control + F5 in Visual Studio: it will launch the application without attaching a debugger.

+6
source

Source: https://habr.com/ru/post/949230/


All Articles