2013-02-03 54 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