I want to use the Windows Phone sensors to move a ball in a Windows Phone game. I tried to move the ball with the accelerometer, but the ball doesn't move correctly if I tilt my Windows Phone device(Lumia 920) in a direction.
For example, if I tilt the device to the left, the ball isn't moving to the left, instead the ball moves very strange. I don't know what I could change in my code so that the ball moves correctly.
What is wrong? Why is the ball not moving in the right direction when I tilt my Windows Phone device?
What should I change so that the ball moves correctly if I tilt the Windows Phone device?
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Motion motion;
Texture2D Ball;
Vector2 BallPos = new Vector2(400, 300);
Vector2 BallVelocity;
void motion_CurrentValueChanged(object sender, SensorReadingEventArgs<MotionReading> e)
{
UpdateUI(e.SensorReading);
}
private void UpdateUI(MotionReading e)
{
float accelerometerX = e.DeviceAcceleration.X;
float accelerometerY = e.DeviceAcceleration.Y;
speed.X += accelReading.X;
speed.Y += -accelReading.Y;
BallPos.X += speed.X *0.05f;
BallPos.Y += speed.Y *0.05f;
}
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
TargetElapsedTime = TimeSpan.FromTicks(333333);
InactiveSleepTime = TimeSpan.FromSeconds(1);
graphics.IsFullScreen = true;
}
protected override void Initialize()
{
if (Motion.IsSupported)
{
motion = new Motion();
motion.TimeBetweenUpdates = TimeSpan.FromMilliseconds(20);
motion.CurrentValueChanged += new EventHandler<SensorReadingEventArgs<MotionReading>>(motion_CurrentValueChanged);
motion.Start();
}
base.Initialize();
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
Message = Content.Load<SpriteFont>("Arial");
Ball = Content.Load<Texture2D>("ballbig");
}
protected override void Update(GameTime gameTime)
{
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
spriteBatch.Draw(Ball, BallPos, null, Color.White, 0, new Vector2(Ball.Width/2,Ball.Height/2), 1f, SpriteEffects.None,1);
spriteBatch.End();
base.Draw(gameTime);
}
}