   Moving an object using xyz accelerometer values
  Dear All, I am new to this forum and gaming as a whole. I am having a number of problems using accelerometer data to move an object (so as to copy the physical movement of the sensor). I have managed to get the object (sqaure box) to rotate using the gyroscopic xyz orienting values, however it is the moving of the box that I am having problems with. I am using the XSens MTx sensors. I will explain what I have done so far by showing the code.Game1 Class-----------using System;using System.Collections.Generic;using System.Linq;using Microsoft.Xna.Framework;using Microsoft.Xna.Framework.Audio;using Microsoft.Xna.Framework.Content;using Microsoft.Xna.Framework.GamerServices;using Microsoft.Xna.Framework.Graphics;using Microsoft.Xna.Framework.Input;using Microsoft.Xna.Framework.Media;using Microsoft.Xna.Framework.Net;using Microsoft.Xna.Framework.Storage;namespace XSENS_JMU_Cube{    /// <summary>    /// This is the main type for your game    /// </summary>    public class Game1 : Microsoft.Xna.Framework.Game    {   GraphicsDeviceManager graphics;   SpriteBatch spriteBatch;   Motion_Object myMotion_Object;   private Xsens_Manager xsens; State state = new State();public Game1()   {  graphics = new GraphicsDeviceManager(this);  Content.RootDirectory = "Content";    //modelPosition.position = Vector3.Zero;  xsens = new Xsens_Manager(this);  xsens.connect();  state.Position = Vector3.Zero;  state.Velocity = Vector3.Zero;   }   /// <summary>   /// Allows the game to perform any initialization it needs to before starting to run.   /// This is where it can query for any required services and load any non-graphic   /// related content.  Calling base.Initialize will enumerate through any components   /// and initialize them as well.   /// </summary>   protected override void Initialize()   {  // TODO: Add your initialization logic here  base.Initialize();   }   // Set the 3D model to draw.   //Model myModel;   // The aspect ratio determines how to scale 3d to 2d projection.   /// <summary>   /// If the aspect ration of the back buffer is widescreen and the aspect ratio of   /// the owner's display is not, the Xbox 360 will add black bars at the top of the   /// display so that the entire back buffer is on screen. To avoid letterboxing,    /// developers   /// </summary>   float aspectRatio;   /// <summary>   /// This variable contains the roll value recieved from the MTx   /// </summary> /// <summary>   /// LoadContent will be called once per game and is the place to load   /// all of your content.   /// </summary>   protected override void LoadContent()   {  // Create a new SpriteBatch, which can be used to draw textures.  spriteBatch = new SpriteBatch(GraphicsDevice);//load the JMU XYZ cube   //myModel = Content.Load<Model>("Models\\cube");  myMotion_Object = new Motion_Object(Content.Load<Model>("Models\\cube"));  aspectRatio = graphics.GraphicsDevice.Viewport.AspectRatio;   }   /// <summary>   /// UnloadContent will be called once per game and is the place to unload   /// all content.   /// </summary>   protected override void UnloadContent()   {  // TODO: Unload any non ContentManager content here   }   //// Set the position of the model in world space, and set the rotation.   //Vector3 modelPosition = Vector3.Zero;   //float modelRotation = 0.0f;   // Set the position of the camera in world space, for our view matrix.   Vector3 cameraPosition = new Vector3(0.0f, 50.0f, 100.0f);   private float t = 0.0f;   private State _newState; /// <summary>   /// Allows the game to run logic such as updating the world,   /// checking for collisions, gathering input, and playing audio.   /// </summary>   /// <param name="gameTime">Provides a snapshot of timing values.</param>   protected override void Update(GameTime gameTime)   {    // Allows the game to exit  if (Keyboard.GetState().IsKeyDown(Keys.Escape)) this.Exit();  t = (float)gameTime.ElapsedGameTime.TotalSeconds;  float dt = (float)t + 0.1f;    state.Position = new Vector3( (float)Convert.ToDouble(xsens.acceleration_X), (float)Convert.ToDouble(xsens.acceleration_Y), (float)Convert.ToDouble(xsens.acceleration_Z));  _newState = myMotion_Object.integrate(state, t, dt);  t += dt;  state.Position = _newState.Position;  // Get some input.  UpdateInput();  base.Update(gameTime);   }   protected void UpdateInput()   {  // Get the game pad state.  KeyboardState currentKeyState = Keyboard.GetState();  // Create some velocity if the right trigger is down.  //Vector3 modelVelocityAdd = Vector3.Zero;  //// Find out what direction we should be thrusting, using rotation.  //modelVelocityAdd.X = -(float)Math.Sin(modelRotation);  //modelVelocityAdd.Y = -(float)Math.Sin(modelRotation);  //modelVelocityAdd.Z = -(float)Math.Cos(modelRotation);  //if (currentKeyState.IsKeyDown(Keys.W))  //    modelVelocityAdd *= 1;  //// Finally, add this vector to our velocity.  //modelVelocity += modelVelocityAdd;  // In case you get lost, press A to warp back to the center.  if (currentKeyState.IsKeyDown(Keys.Enter))  { state.Position = Vector3.Zero;  }   }   /// <summary>   /// This is called when the game should draw itself.   /// </summary>   /// <param name="gameTime">Provides a snapshot of timing values.</param>   protected override void Draw(GameTime gameTime)   {  GraphicsDevice.Clear(Color.CornflowerBlue);  // Copy any parent transforms.  Matrix[] transforms = new Matrix[myMotion_Object.model.Bones.Count];  myMotion_Object.model.CopyAbsoluteBoneTransformsTo(transforms);  // Draw the model. A model can have multiple meshes, so loop.  foreach (ModelMesh mesh in myMotion_Object.model.Meshes)  { // This is where the mesh orientation is set, as well as our camera and projection. foreach (BasicEffect effect in mesh.Effects) {//You will notice that I have swapped the order or YPR to YRP. This is so that //the xsens sensor, when being moved, looks the same in XNA. This probably needs//to be changed at some point. //There are two ways to calculate angles - degrees and radians. Radians are used//in XNA because they are easier to computer.//1 Radian = 57.3 degrees; 1 Degree = 0.0174532 radians roughlyeffect.World = transforms[mesh.ParentBone.Index] *Matrix.CreateFromYawPitchRoll(    (MathHelper.ToRadians((float)Convert.ToDouble(xsens.yaw))),    (MathHelper.ToRadians((float)Convert.ToDouble(xsens.roll))),    (MathHelper.ToRadians((float)Convert.ToDouble(xsens.pitch))))* Matrix.CreateTranslation(state.Position);effect.View = Matrix.CreateLookAt(cameraPosition, Vector3.Zero, Vector3.Up);effect.Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f),    aspectRatio, 1.0f, 10000.0f); } mesh.Draw();  }  base.Draw(gameTime);  }    }}Motion Object - this code was originally developed by Glenn Fiedler http://gafferongames.com/game-physics/integration-basics/---------------using System;using System.Collections.Generic;using System.Linq;using Microsoft.Xna.Framework;using Microsoft.Xna.Framework.Audio;using Microsoft.Xna.Framework.Content;using Microsoft.Xna.Framework.GamerServices;using Microsoft.Xna.Framework.Graphics;using Microsoft.Xna.Framework.Input;using Microsoft.Xna.Framework.Media;using Microsoft.Xna.Framework.Net;using Microsoft.Xna.Framework.Storage;namespace XSENS_JMU_Cube{    class Motion_Object    {   private Model _model ;   //// Set the velocity of the model, applied each frame to the model's position.   //Vector3 modelVelocity = Vector3.Zero;   State state = new State();   State derivedState = new State();   public Motion_Object(Model model )   {  this._model = model;   }   public Model model   {  get { return _model; }   }//public void setModelPosition(Vector3 pos, Vector3 vel){  //    this._modelPosition.position = pos;  //    this._modelPosition.velocity = vel;   //}   private State evaluate(State initial, float t, float dt, State d)   {  State state = new State();  state.Position = new Vector3( initial.Position.X + d.Position.X * dt, initial.Position.Y + d.Position.Y * dt, initial.Position.Z + d.Position.Z * dt);  state.Velocity = new Vector3( initial.Velocity.X + d.Velocity.X * dt, initial.Velocity.Y + d.Velocity.Y * dt, initial.Velocity.Z + d.Velocity.Z * dt);  State output = new State();   output.Position = new Vector3( state.Velocity.X, state.Velocity.Y, state.Velocity.Z);  output.Velocity = new Vector3( acceleration(state.Position.X, state.Velocity.X, t + dt), acceleration(state.Position.Y, state.Velocity.Y, t + dt), acceleration(state.Position.Z, state.Velocity.Z, t + dt));    return output;   }   private float acceleration(float position, float velocity, float t)   {  const float k = 10;  const float b = 1;  return -k * position - b * velocity;   }   public State integrate(State state, float t, float dt)   {  State _newState = new State();  State a = evaluate(state, t, 0.0f, new State());  State b = evaluate(state, t, dt * 0.5f, a);  State c = evaluate(state, t, dt * 0.5f, b);  State d = evaluate(state, t, dt, c);  float dxdt = 1.0f / 6.0f * (a.Position.X + 2.0f * (b.Position.X + c.Position.X) + d.Position.X);  float dydt = 1.0f / 6.0f * (a.Position.Y + 2.0f * (b.Position.Y + c.Position.Y) + d.Position.Y);  float dzdt = 1.0f / 6.0f * (a.Position.Z + 2.0f * (b.Position.Z + c.Position.Z) + d.Position.Z);  _newState.Position = new Vector3( state.Position.X + dxdt * dt, state.Position.Y + dydt * dt, state.Position.Z + dzdt * dt);  return _newState;   }    }}State Class-----------using System;using System.Collections.Generic;using System.Linq;using System.Text;using Microsoft.Xna.Framework;namespace XSENS_JMU_Cube{    class State    {   private Vector3 _position;   private Vector3 _velocity;   public State()   {  _position = new Vector3();  _velocity = new Vector3();   }   public Vector3 Position   {  get { return _position; }  set { _position = value; }   }   public Vector3 Velocity   {  get { return _velocity; }  set { _velocity = value; }   }    }}I would really appreciate an pointers on how I can get this the motion to work. Just to be clear when a physically move my sensor along either the XYZ axis (not rotate, I have this working) I want the cube in XNA to follow.Thank you in advance for your time and effort. Kind Regards   
  Dear All, I have simplified the code a little, but I am still having problems. In the code example below I am only looking at the X axis for now. The problem I am having is that when I tilt the sensor through positive and negative X. The problem is that when I tilt it and keep it in that position my cube in XNA continually moves in that direction. This is not what I want. I only want the cube in XNA to move in relation to my sensor moving along the positive and negative X axis, i.e. forwards and backwards along the axis as I move the sensor. In this sense the cube in XNA mimics the movements of my physical sensor. The position code is in my update method. I am using an XSENS MTx sensor which has a +-50 m/s2 (5g). So the values are returned in the following format as an example -2.3 or +2.3. These values can move in eiher direction (+-) between 0 and 50. Here is my new code. I would be really greatful if anyone could provide me with some help. using System;using System.Collections.Generic;using Microsoft.Xna.Framework;using Microsoft.Xna.Framework.Audio;using Microsoft.Xna.Framework.Content;using Microsoft.Xna.Framework.Graphics;using Microsoft.Xna.Framework.Input;using Microsoft.Xna.Framework.Storage;public class Game1 : Microsoft.Xna.Framework.Game{    GraphicsDeviceManager graphics;    ContentManager content;    private Xsens_Manager xsens;    public Game1()    {   graphics = new GraphicsDeviceManager(this);   content = new ContentManager(Services);   xsens = new Xsens_Manager(this);   xsens.connect();    }    protected override void Initialize()    {   base.Initialize();    }    // Specify the 3D model to draw.    Model myModel;    // The aspect ratio determines how to scale 3d to 2d projection.    float aspectRatio;    protected override void LoadContent()    {   myModel = content.Load<Model>("Content\\Models\\cube");   aspectRatio = graphics.GraphicsDevice.Viewport.Width /  graphics.GraphicsDevice.Viewport.Height;    }    protected override void UnloadContent()    {   content.Unload();    }    // Set the velocity of the model, applied each frame to the model's position.    //Vector3 modelVelocity = Vector3.Zero;    float time = 0.0f;    protected override void Update(GameTime gameTime)    {   // Allows the game to exit   if (Keyboard.GetState().IsKeyDown(Keys.Escape))  this.Exit();    float velocity = 0.0f;   if ((float)Convert.ToDouble(xsens.acceleration_X) > -1.0f)  modelPosition.Z = modelPosition.Z + 0.0f;   else   {  //v = a*t  velocity = (float)Convert.ToDouble(xsens.acceleration_X) * time;  //x = v*t  modelPosition.Z += -(velocity * time) + -0.5f;   }   if ((float)Convert.ToDouble(xsens.acceleration_X) < 1.0f)  modelPosition.Z = modelPosition.Z + 0.0f;   else   {  velocity = (float)Convert.ToDouble(xsens.acceleration_X) * time;  modelPosition.Z += (velocity * time) + 0.5f;   }   time = (float)gameTime.ElapsedGameTime.TotalSeconds;   // Get some input.   UpdateInput();   OutputAccelData();   base.Update(gameTime);    }    protected void UpdateInput()    {   // Allows the game to exit   if (Keyboard.GetState().IsKeyDown(Keys.Enter))  modelPosition = Vector3.Zero;//if ((float)Convert.ToDouble(xsens.acceleration_X) < -1.0f)   //    modelPosition.X = modelPosition.X + (float)Convert.ToDouble(xsens.acceleration_X);    ////Test code to show Simon how code works.    //if (Keyboard.GetState().IsKeyDown(Keys.Left))   //    modelPosition.X = modelPosition.X + -0.5;   //else if (Keyboard.GetState().IsKeyDown(Keys.Right))   //    modelPosition.X = modelPosition.X + 0.5f;   //else if (Keyboard.GetState().IsKeyDown(Keys.Up))   //    modelPosition.Y = modelPosition.Y + -0.5f;   //else if (Keyboard.GetState().IsKeyDown(Keys.Down))   //    modelPosition.Y = modelPosition.Y + 0.5f;   //else if (Keyboard.GetState().IsKeyDown(Keys.A))   //    modelPosition.Z = modelPosition.Z + -0.5f;   //else if (Keyboard.GetState().IsKeyDown(Keys.D))   //    modelPosition.Z = modelPosition.Z + 0.5f;    }    protected void OutputAccelData()    {   System.Console.WriteLine("Accel X: " + xsens.acceleration_X);   System.Console.WriteLine("Accel Y: " + xsens.acceleration_Y);   System.Console.WriteLine("Accel Z: " + xsens.acceleration_Z);    }    // Set the position of the model in world space, and set the rotation.    Vector3 modelPosition = Vector3.Zero;    // Set the position of the Camera in world space, for our view matrix.    Vector3 cameraPosition = new Vector3(0.0f, 50.0f, 100.0f);    protected override void Draw(GameTime gameTime)    {   graphics.GraphicsDevice.Clear(Color.CornflowerBlue);   // Copy any parent transforms.   Matrix[] transforms = new Matrix[myModel.Bones.Count];   myModel.CopyAbsoluteBoneTransformsTo(transforms);   // Draw the model. A model can have multiple meshes, so loop.   foreach (ModelMesh mesh in myModel.Meshes)   {  // This is where the mesh orientation is set, as well as our camera and projection.  foreach (BasicEffect effect in mesh.Effects)  { effect.EnableDefaultLighting(); //You will notice that I have swapped the order or YPR to YRP. This is so that  //the xsens sensor, when being moved, looks the same in XNA. This probably needs //to be changed at some point.  //There are two ways to calculate angles - degrees and radians. Radians are used //in XNA because they are easier to computer. //1 Radian = 57.3 degrees; 1 Degree = 0.0174532 radians roughly effect.World = transforms[mesh.ParentBone.Index] *Matrix.CreateFromYawPitchRoll(    (MathHelper.ToRadians((float)Convert.ToDouble(xsens.yaw))),    (MathHelper.ToRadians((float)Convert.ToDouble(xsens.roll))),    (MathHelper.ToRadians((float)Convert.ToDouble(xsens.pitch))))* Matrix.CreateTranslation(modelPosition); effect.View = Matrix.CreateLookAt(cameraPosition, Vector3.Zero, Vector3.Up); effect.Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f),aspectRatio, 1.0f, 10000.0f);  }  // Draw the mesh, using the effects set above.  mesh.Draw();   }   base.Draw(gameTime);    }}   ;  So you're trying to use accelerometer values to change the position of an object? That's going to be extremely inaccurate; the accelerometers aren't going to be accurate enough, and it's going to be difficult to get rid of the noise. This is why there's no Wii games that use the accelerometer values for positioning.   ;  Hello Evil Steve, XSens already have a motion capture solution using the MTx so I presume that it is possible. Would I need to use the other data provided, such as the gyroscopic information to achieve this. My initial thoughts is that I would not use the accelerometer values directly but as part of a formula for positioning based on some of the mathematical formulas available for motion. I have tried in part to do this in my code, but obviously I am missing something. In my code it is easy to achieve what I want using the key input, but it is obvously a bit more tricky with accelerometer data. Any suggestions on how I might achieve this. Kind Regards, Paul   