简体   繁体   中英

how to move 3d object in XNA?

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:

float dirX = (float)Math.Sin(angle);
float dirZ = (float)Math.Cos(angle);

position += new Vector3(dirX, 0, dirZ); 

Then, you should multiply your transformation matrices in the correct order:

Scale * Rotation * Translation

Which in your case translates to:

// this will rotate car around the Y axis, and then translate it to correct location
world = Matrix.CreateRotationY(angle) * Matrix.CreateTranslation(position);

One suggestion, do as A-Type suggested, and use direction * speed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM