如何在 XNA 中移动 3d 对象? [英] how to move 3d object in XNA?
问题描述
我想移动一个 3d 汽车模型,当我按下向左或向右箭头键时,我改变了角度,当我按下向上箭头时,汽车就会行驶.
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;
}
}
这是计算部分,但显然我还需要在屏幕上移动汽车.我想让汽车向前移动,而不是向上移动,所以我想我应该在 X 轴上将它旋转 90 度,而且我想在按向左或向右键时旋转汽车.
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.
我写了这段代码:
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?
推荐答案
您应该意识到您的 Y 轴实际上是向上",而不是向前"(按照惯例).虽然此问题有很多解决方案,但解决您的问题的最快方法是:
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
在你的情况下翻译成:
// this will rotate car around the Y axis, and then translate it to correct location
world = Matrix.CreateRotationY(angle) * Matrix.CreateTranslation(position);
一个建议,按照A-Type的建议去做,使用方向*速度.
One suggestion, do as A-Type suggested, and use direction * speed.
这篇关于如何在 XNA 中移动 3d 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!