Windows Phone: An Accelerator-Based App in 5 Minutes!
Join the DZone community and get the full member experience.
Join For FreeYou can read my previous article about the Accelerometer in more detail.
This can be quite useful for game scenarios. It can also be useful in productivity applications where the developer is using additional forms of user interaction to offer greater usability or innovation.
Let’s Build Something!
In
this video, I build a very simple application that leverages
the Accelerometer to move a circle around on the screen. Hopefully this
simple sample is enough to get you started to leverage the Accelerometer
in your application.
In the video, I left out all the frills. Using the
Accelerometer really is as simple as a few lines of code. Just be sure
and reference XNA and Microsoft.Devices.Sensors to access the capabilities.
What I don’t do is leverage the new Motion API
that unifies multiple sensors to provide information about orientation
and motion. This sample is the bare bones “how to use accelerometer” but
it is worth saying that your application might benefit most from the Motion API.
The Code
I really love how little code is necessary to accomplish a complex task.
In the code above, we need only Start() the Accelerometer for it to begin working. When the sensor detects a tilt, it raises the CurrentValueChanged event. It is there we handle the delta provided from the event (the amount changed since the last event was raised).
The only thing to remember is that we need to return from the Accelerometer’s thread to the UI thread. I discuss this also here. But, in short, we accomplish this by executing the logic in the handler inside the Dispatcher for the application.
Conclusion
Windows Phone developers don’t just have a bevy of sensors in their arsenal, they have XAML. And you would be remiss to dismiss XAML as a simple declarative UI technology (although it is that). XAML in the Silverlight Engine gives developers tools and controls to perform many complex and amazing tasks with ease. Many of these tasks, including the use of TranslateTransform (in this video) can take benefit of the local hardware.
Ready to tilt?
Best of luck!
Source: http://blog.jerrynixon.com/2012/02/wp7-sample-accelerator-based-app-in-5.html
Opinions expressed by DZone contributors are their own.
Comments