how to move 3d object in XNA?

夙愿已清 提交于 2019-12-13 19:11:05

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/9240680/how-to-move-3d-object-in-xna

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!