Windows Phone 7 Game Development: A Beginner’s Guide (Accelerometer)

Hello all. Keith here again, as promised. Bounce is now available, for free, on Zune marketplace. The current version contains some game-play bugs but an update will fix these in the next few days.

 

This is to be my first article on common problems faced by developers new to WP7. I am by no means an expert but I found that most of the articles and posts relating to the topics I will cover weren’t coherent or were too advanced for a developer new to WP7.
I will tell you the problems that I encountered, show you my solutions and provide links to other useful articles on the subjects. If you are new to WP7 development I suggest checking out the Windows Phone 7 Training Kit. Although you may not follow it exactly, it does provide a good base to get you going.

The Accelerometer:

The accelerometer reads the current force of acceleration acting on the phone on all 3 axes. This data is stored as a 3D vector. While the phone is stationary the only force of acceleration is gravity. I had to do research into what the accelerometer readings would be and what these would mean. My findings were that when the phone is still, the readings due to gravity is a vector whose magnitude is near 1. This varies around 1 due to the slight variations in gravity between places and altitudes. The accelerometer also generates a lot of “noise data”. This is something to keep in mind as you may need to perform some smoothing on it (a quick search will yield lots of info.). I did not require any as the data was used in such a way that it did not matter.

 

Anyway a picture says a thousand words so here is a simple illustration of the readings, due to gravity, to expect. Please note the magnitude of 1 in the following readings will not be exact (as stated above). It is used for illustrative purposes only. There are far more detailed descriptions of the readings to expect but I wanted to keep this simple.

 

The blue rectangle represents the phone screen. The red arrow points to top of phone.

WP7 Accelerometer Readings

Readings due to gravity

 

Another thing to note is that changes in accelerometer readings do not count as input to the device. This is to prevent accidental activation of the phone from user movement. This means that the screensaver may have to be disabled while your application is running. If you do this you must be re-enable it on leaving your game to pass the validation process. The code required for this is below.

 

Add this using statement to your game class:

using Microsoft.Xna.Framework.GamerServices;

Declare a bool in your class to hold the original screen saver setting:

bool m_screenSaverEnabled;

On activation of your game add:

m_screenSaverEnabled = Guide.IsScreenSaverEnabled;
Guide.IsScreenSaverEnabled = false;

On deactivation of your game add:

Guide.IsScreenSaverEnabled = m_screenSaverEnabled;

 

 

Accelerometer with the emulator:

As I am a student I could not afford a WP7 device to test on. This meant I had to rely on the emulator which has no support for accelerometer input or simulation. This was a major problem as the main user input for my game was accelerometer input.

 

After scouring the internet I came across a few solutions:

1. Use the keyboard or mouse to simulate input.

2. Use a game controller (Wii-mote, PS Move, etc.).

3. Use augmented reality (courtesy of Codeplex). Nikos Kastellano’s blog, Codeplex Download

4. Use Maciej Grabek’s accelerometer plugin for the emulator. The Code Project, Original source

 

As I was only learning XNA and have a reasonable grasp of 3D vectors, I decided to use the keyboard to simulate accelerometer input. A basic implementation of this can be found in the sample game “MarbleMaze” which is part of the “Windows Phone 7 Training Kit” mentioned above. This example gives a good idea of the approach to take to this solution but is unnecessarily complicated in its implementation and somewhat simplistic in its handling of input (although it could be altered or expanded upon). It simply adds or subtracts from one of the accelerometer Vector values (x, y or z) when the arrow keys are pressed.

 

What I really required was an interface class, similar to this one, which was easier to understand and performed rotations around each of the axes. This would give me the simulated tilt which I was after. I ended up writing a class which checks whether it is running on the emulator or the phone and decides what input data to collect and how to manipulate it. I wrote a few simple rotation methods into the class to simulate tilting. They operate around mathematical axes, not the phones axes.

 

Accelerometer Handler Source: (Right-click and select “save link as…”)

AccelerometerHandeler.cs

 

For the accelerometer handler to work you must change the namespace to match your project and add references to Microsoft.Devices.Sensors and Microsoft.Phone to your project. Microsoft.Devices.Sensors allows use of the accelerometer and Microsoft.Phone allows you to check if the active device is the phone.

 

Required References

Required References

To add these references right-click on “References” (just above the highlighted items), select “add reference”, select the .NET tab and find them in the list.

 

The class works like this:

An object of type AccelerometerHandler is created. During construction it checks what device type it is running on. If it is running on the phone it creates a link to the in-built accelerometer interface, adds a new event handler to the accelerometer (to handle what to do when the readings change) and activates the accelerometer. Otherwise it just sets the readings to default values. The event handler just sets the class’ current reading to the current accelerometer data.

 

During your game’s update method the currentReading() method is called. If the active device is the phone the current reading is normalized and returned. If the active device is the emulator keyboard input is read and rotations are performed. The resultant vector is normalized and returned. The class provides active() and stopAccelerometer() methods to start and stop the accelerometer, though they are not really necessary as these are handled autonomously.

 

To activate keyboard input when using the emulator press the “page up” key while the emulator is active.

 

I hope you found this useful.

Be back soon…

About the Author

Keith Cully

Keith is a dedicated, hardworking individual. Although he started out as a bespoke furniture maker, hard times and a huge interest in technology led him to become a computer games developer (I know it sounds random). Keith is currently attending the Computer Games Development course at I.T. Carlow and has skills in a number of languages. Keith is especially interested in mobile platforms and is currently developing for Windows Phone 7. Follow me on twitter for updates or check out my website.

Visit Website

8 Comments

  1. I’m glad that you liked my project. In new version of Windows Phone Developer Tools (Mango) Accelerometer Emulator will be part of WP7 Emulator. Its funny that it looks very similar to mine 🙂

    • Author

      Good to hear. I was half way through development when I heard about the beta so I didn’t want to update until I was finished.

  2. Kevin Beirne August 9, 2011

    Hey Keith. REMEMBER ME!? Thanks for that, been interested in getting into the Windows Phone when we get back to college so this was pretty interesting. Look forward to seeing everyone next term.

    • Author

      I think I vaguely recall someone from Cork called Kevin but I’m not quite sure… Ha. It’s a decent platform and there’s a very helpful community of developers. Anyway I’ve been working on XNA all Summer so if you do start developing for it I can probably give you a few tips. Chat to you in a few weeks anyway.

      • Iulian Todirica June 8, 2012

        Hey Keith, Just finished first year in ITC. Good thing you guys have going on here but howcome there aren’t any more updates? as for the accelerometer, it does not seem to work on my emulator on HTC HD7, even though I also tried the sample from msdn…I have currently 3 silverlight apps published and working on forth for the app me up program but after i want to turn one of my projects which is wp7 already to a release and the current input is touch gestures-drag and tap. trying to make my car steer by tilting the phone. any help appreciated

        • Author
          Keith Cully June 13, 2012

          Hey Iulian.
          The site hasn’t been updated as no one has time. 3rd year was a killer (There was talk of blogging about setting up PhysX with Ogre3D but no one had time) and we’re all in internships now.

          This thread is extremely outdated as the emulator now has built in accelerometer emulation.
          To use this, select the “>>” icon from the bar which you close the emulator from.

          I would strongly recommend testing on a device though as you get lots of data noise, even while holding the phone stationary.

          • Iulian Todirica June 13, 2012

            tested it with the built in accelerometer for the emulator and on my htc hd7 as well…wont work tho

Trackbacks for this post

  1. An idler is a watch that wants both hands; As useless if it goes as when it stands….

    And he by no uncommon lot Was famed for virtues he had not….