2013-02-03 33 views
1

好吧,我是XNA编程的noob,对我来说很裸露。我已经按照教程介绍了如何使微软网站上的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; 
} 

有人能告诉我为什么相机不移动其旋转的方式吗?或者有人可以给我这个该死的代码来制作一个吗?谢谢。

回答

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的相反,它应该使用你的方向指向看起来是你的transformationReference变量。

例如,向前移动相机对着方式:

if (IsKeyDown(Keys.W)) 
    avatarPosition += transformedReference; 

然而,由于transformedReference出现变量进行归一化,也可以不移动化身你希望的距离。在这种情况下,简单地乘以一些常数MOVEMENT_SPEED类似的东西:

if (IsKeyDown(Keys.W)) 
    avatarPosition += transformedReference * MOVEMENT_SPEED; 
+0

谢谢!按照你所说的话,我可以将照相机向前和向后移动,但是我将如何从它所面对的方向左右移动照相机?你能举个例子吗? – Josh

+0

我本来希望左右两边很容易搞清楚。我很抱歉他们没有。要找到(x,y)的垂直向量,只需交换条件并取反:(y,-x)或(-y,x)在你的情况中,由于你正在处理3d向量,假设y值isn在那里,只能在x和z方面进行操作。我建议你刷一些矢量数学http://programmedlessons.org/VectorLessons/index.html它会让你的生活更容易,如果你要编程3D游戏。 –

+0

谢谢分配人!知道了所有钉。 – Josh