This week, we’ll be using the accelerometer to move the player around. For those of you without a device, this one is going to be a bit tricky, as the emulator has no support for the accelerometer at this time. To do this, we’ll put in a check to see whether we are running on a device or an emulator, and use the accelerometer if it’s the device, and multi-touch if it’s the emulator. To begin, grab the latest version of the code from the SkyDrive share.
In order to use the accelerometer, we’ll need to add an assembly reference to Microsoft.Devices.Sensors, and to test if the game is running on the emulator or a device, we add a reference to Microsoft.Phone. To add the reference, right-click on the references folder in the TriangleShooter project, choose Add Reference, and choose the two references from the list. Additionally, the following Using statement will need to be added for easy access to the Accelerometer:
We’ll create a variable for the Acceleromter called accelerometer:
We’ll check to see if we are running on the device, and if so, initialize the variable, set up a method that will handle the accelerometer, and start the monitoring.
The method monitoring the reading changed event will update the position and rotation similar to the method we used around multi-touch.
If you make only these changes, the accelerometer will work, but the player won’t move around, because we never actually set the player speed. We can update the player initialization to the following to make that happen.
Finally, we’ll update the UpdatePlayer method to check if the game is running on the emulator, and use the multi-touch if it is.
Now we run with multi-touch on the emulator, and the accelerometer on the device.
At this point, we’re pretty complete as far as the game goes. There are a few things we can do to clean up the code, and to improve the gameplay, and I will post updates as I continue with the project, but next week, we’ll be introducing a new project, so stay tuned.
Download the latest version of the source code.