好的,我是XNA编程中的菜鸟,对我来说很光鲜。我已经在微软网站上关注如何让第一人称相机旋转并在XNA中移动3D世界的教程。但是当我沿着它的Y轴旋转相机时,它不会移动它旋转/面对的方向,而是移动它就像它面向它最初面对的方向一样。
这是我的代码:
static Vector3 avatarPosition = new Vector3(0, 0, 0);
static Vector3 cameraPosition = avatarPosition;
Vector3 cameraReference = new Vector3(10, 0, 0);
// Create a vector pointing the direction the camera is facing.
Matrix world = Matrix.CreateWorld(new Vector3(0, -1, 0), Vector3.Forward, Vector3.Up);
Matrix rotationMatrix = Matrix.CreateRotationY(MathHelper.ToRadians(0));
int Rot = 0;
Vector3 worldVector = new Vector3(5,-2, 0);
Matrix view, proj;
Vector3 cameraLookat;
Update()
{
world = Matrix.CreateWorld(worldVector, Vector3.Forward, Vector3.Up);
if (IsKeyDown(Keys.W))
avatarPosition += new Vector3(0.2f, 0f, 0);
if (IsKeyDown(Keys.S))
avatarPosition += new Vector3(-0.2f, 0f, 0);
if (IsKeyDown(Keys.A))
avatarPosition += new Vector3(0f, 0f, -0.2f);
if (IsKeyDown(Keys.D))
avatarPosition += new Vector3(0f, 0f, 0.2f);
if (IsKeyDown(Keys.Left))
Rot += 1;
if (IsKeyDown(Keys.Right))
Rot += -1;
rotationMatrix = Matrix.CreateRotationY(MathHelper.ToRadians(Rot));
// Create a vector pointing the direction the camera is facing.
Vector3 transformedReference = Vector3.Transform(cameraReference, rotationMatrix);
// Calculate the position the camera is looking at.
cameraLookat = transformedReference + cameraPosition;
// Set up the view matrix and projection matrix.
view = Matrix.CreateLookAt(cameraPosition, cameraLookat, new Vector3(0.0f, 1.0f, 0.0f));
proj = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45), graphics.GraphicsDevice.Viewport.AspectRatio,
0.1f, 1000);
cameraPosition = avatarPosition;
}
有人可以告诉我为什么相机不会像旋转那样移动吗?或者有人可以给我一个该死的代码来制作一个?感谢。
答案 0 :(得分:2)
我看到您遇到的问题来自代码的这个区域:
if (IsKeyDown(Keys.W))
avatarPosition += new Vector3(0.2f, 0f, 0);
if (IsKeyDown(Keys.S))
avatarPosition += new Vector3(-0.2f, 0f, 0);
if (IsKeyDown(Keys.A))
avatarPosition += new Vector3(0f, 0f, -0.2f);
if (IsKeyDown(Keys.D))
avatarPosition += new Vector3(0f, 0f, 0.2f);
不是直接沿x轴或z轴平移avatarPosition,而应该使用你指向的方向,它似乎是你的transformedReference变量。
例如,要向前移动相机的方向:
if (IsKeyDown(Keys.W))
avatarPosition += transformedReference;
但是,由于transformedReference变量似乎已经规范化,因此它可能无法将化身移动到您希望的距离。在这种情况下,简单地将它乘以一些常量MOVEMENT_SPEED,如下所示:
if (IsKeyDown(Keys.W))
avatarPosition += transformedReference * MOVEMENT_SPEED;