1
\$\begingroup\$

Currently I have a playerWorld matrix which holds the position of my player, just a simple sphere. When I press a key to move the model, it does some crazy thing and flies off the screen really fast, and not even in the direction I want it to go.

    if (kbs.IsKeyDown(Keys.W))
        {
            playerWorld += Matrix.CreateTranslation(playerWorld.Forward * elapsed);
        }

Why is this happening? elapsed is a float variable:

    float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;

Here is the draw code, maybe it's being drawn wrong?

    public void Render(ThirdPersonCam cam)
    {
        foreach (ModelMesh mesh in playerModel.Meshes)
        {
            foreach (BasicEffect effect in mesh.Effects)
            {
                effect.View = cam.view;
                effect.Projection = cam.proj;
                effect.World = playerTransforms[mesh.ParentBone.Index] * playerWorld;
            }
            mesh.Draw();
        }
    }
\$\endgroup\$

2 Answers 2

2
\$\begingroup\$

When adding (combining) the movement or rotation (or scale) of two matrices together the arithmetic to apply on them is multiplication rather than addition.

change your += to *= and your original code will work as expected.

if (kbs.IsKeyDown(Keys.W))
    {
        playerWorld *= Matrix.CreateTranslation(playerWorld.Forward * elapsed);
    }

one matrix multiplied by another matrix results in what you would conceptualize as adding the SRT of one matrix to the SRT of the second. (SRT is Scale/Rotation/Translation)

\$\endgroup\$
2
  • \$\begingroup\$ Alright that worked. Now my camera position is weird. Vector3 camPosition = objectToFollow.Translation + (objectToFollow.Backward * 5) + (objectToFollow.Up * 2); This is taking position of my model, not following behind it so I can't see it \$\endgroup\$ Commented Jun 16, 2013 at 4:59
  • \$\begingroup\$ Nevermind. I changed Backward to * 10 and it works perfectly \$\endgroup\$ Commented Jun 16, 2013 at 6:34
2
\$\begingroup\$

Use a vector to store translation and build the matrix from it.

   if (kbs.IsKeyDown(Keys.W))
      {
          playerPos += playerForward * speed * elapsed; 
      }      

   playerWorld = Matrix.CreateScale(playerScale) 
               * Matrix.CreateFromQuaternion(playerRotation)
               * Matrix.CreateTranslation(playerPos);
\$\endgroup\$
1
  • \$\begingroup\$ Oh I didn't even think about putting a matrix in there for rotation.. \$\endgroup\$ Commented Jun 15, 2013 at 9:08

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .