Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows Phone 8 Accelerometer events

I'm making my first game for Windows Phone (XNA). I use Accelerometer to change the position of a crosshair on the screen:

Position of crosshair

Here is the code in my Initialize() function (note that Accelerometer is local variable declared only in this function):

Accelerometer accelerometer = new Accelerometer();
accelerometer.CurrentValueChanged += accelerometer_CurrentValueChanged;
accelerometer.Start();

And the 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 Windows Phone Emulator, and on my Nokia Lumia 520 connected to the computer and launching from Visual Studio, however when I launch the game in the phone (not connected to the computer), the accelerometer_CurrentValueChanged event appears to be called only once, on application startup.

My solution was to make the accelerometer a member of my Game class, then code in Initialize() like this:

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 application launched from VS and normally, even on the same device?

like image 540
Przemen Avatar asked Jul 11 '13 14:07

Przemen


1 Answers

Why this solution works?

This solution works because you're keeping a reference to the accelerometer. Windows Phone applications, like all .NET applications, use an automated system for memory management. A background process, called garbage collector, inspects the objects in a regular basis, detects those who are not referenced anymore, and clean them. If you declare accelerometer as a local variable, it won't be referenced anymore when the function exits, and will therefore be cleaned. When you declare it as a member of your class, it will be alive for as long as your class lives.

Why the difference between application launched from VS and normally, on the same device?

When launching the code from Visual Studio, a debugger is attached. To help you debugging, it has some impacts on the way the code executes. Notably, it makes the garbage collector way less aggressive. It explains why you didn't have this issue when testing with the debugger attached. Note that you can achieve the same result by pressing Control + F5 in Visual Studio: it'll start the application without attaching the debugger.

like image 116
Kevin Gosse Avatar answered Oct 18 '22 22:10

Kevin Gosse