简体   繁体   中英

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:

十字准线的位置

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM