Article: Zune HD Accelerometer Basics
by Conkerjo
![]()
This article explains the very basics of using the accelerometer on the ZuneHD using XNA 3.1
Note
This sample uses a build of the TinyEngine at the time it was written.
In this sample I want to show how to move a sprite around using only the Accelerometer for input. We will utilize some of the features of TinyEngine to get us up and running quickly.
XNA Zune Extensions provide a static class called Accelerometer. It provides a GetState method which returns the current state of the Accelerometer as a AccelerometerState type.
public struct AccelerometerState
{
public Vector3 Acceleration { get; }
public bool IsConnected { get; }
public Matrix GetRotation();
}
Note that this class is not available on Windows and must be wrapped in a #if ZUNE conditional compilation statement if trying to develop a cross-platform game.
The Acceleration is a 3 dimensional value of the direction the Accelerometer is moving at the time.< /br>
The GetRotation gives us a Matrix of the rotation of the device. This is great information for tilting the view to the direction of the device, but that's out of scope for this article.
To use this in our code, as we're only moving a simple 2D sprite, we only need the X & Y of the the Acceleration to apply to the Sprites move method.
AccelerometerState state = Accelerometer.GetState();
Vector2 accel = new Vector2(state.Acceleration.X, -state.Acceleration.Y);
this.mrTiny.Move(accel * 100 * elapsed);
The Move method here just simply adds the passed in Vector2 to the current Position of the Sprite.
We then add a Clamp check so that the Sprite doesnt go off screen< /br>
Again, TinyEngine provides us with the Bounds of the Screen. With TinyEngine 0,0 is the center of the screen and not the XNA default of top left.
this.mrTiny.PositionX = MathHelper.Clamp(this.mrTiny.PositionX, this.ScreenBounds.Left, this.ScreenBounds.Right);
this.mrTiny.PositionY = MathHelper.Clamp(this.mrTiny.PositionY, this.ScreenBounds.Top, this.ScreenBounds.Bottom);
And there we have it, you can tilt your Zune HD to move around Mr Tiny.
The code is linked just below.
Source Code (Includes Tiny Engine Source)
Conkerjo - www.conkerjo.com - www.twitter.com/conkerjo (Come up with some generic way to show the author)
March 5th, 2010 - 23:51
Hi. Just wondering if the source is still available? The link appears broken.
Cheers, balog
March 6th, 2010 - 12:56
Hmm, not sure what happened to that build, but you can grab the latest source code from here
http://subversion.assembla.com/svn/tinyengine/