I want to move a 3d car model, when I press the left or right arrow key I change the angle, when I press the up arrow the car drives.
This is the code in the update method:
float dirX = (float)Math.Sin(angle);
float dirY = (float)Math.Cos(angle);
if (Keyboard.GetState().IsKeyDown(Keys.Up))
{
position += new Vector3(-dirX, dirY, 0);
if (Keyboard.GetState().IsKeyDown(Keys.Left))
{
angle += 0.015f;
}
if (Keyboard.GetState().IsKeyDown(Keys.Right))
{
angle -= 0.015f;
}
}
This is the calculating part, but obviously I also need to move the car on the screen.
I want the car to move forward, not up, so I thought I should rotate it 90 degrees on the X axis, and also I want to rotate the car when I press the left or right keys.
I wrote this code:
world = Matrix.CreateTranslation(position) * Matrix.CreateRotationY(angle) * Matrix.CreateFromAxisAngle(Vector3.UnitX, MathHelper.ToRadians(-90));
This code isn’t working, can anybody tell me how can I move it?
You should be aware that your Y axis is actually “up”, not “forward” (by conventions). While this problem has many solutions, quickest way to fix yours is that:
Then, you should multiply your transformation matrices in the correct order:
Which in your case translates to:
One suggestion, do as A-Type suggested, and use direction * speed.