2014-11-01 19 views
1

我正嘗試使用Unity引擎從頭開始創建RTS遊戲。我從這個Unity RTS game tutorial開始,我正在設置相機。基本上我所做的是,我生成[x,0,z]矢量運動。然後我需要將其應用於相機。TransformDirection在創建RTS攝像頭時行爲不如預期

如果相機沒有旋轉,它可以很好地工作 - 但它通常是旋轉的並且必須是可旋轉的。

根據教程and the docs,我可以使用Camera.main.transform.TransformDirection(MyVector)將矢量轉換爲相機的視角。這是我做的:

//Get mouse position 
    float xpos = Input.mousePosition.x; 
    float ypos = Input.mousePosition.y; 
    //Create vector for movement 
    Vector3 movement = new Vector3(0, 0, 0); 

    //horizontal camera movement 
    if (xpos >= 0 && xpos < ResourceManager.ScrollWidth) 
    { 
     movement.x -= ResourceManager.ScrollSpeed; 
    } 
    else if (xpos <= Screen.width && xpos > Screen.width - ResourceManager.ScrollWidth) 
    { 
     movement.x += ResourceManager.ScrollSpeed; 
    } 
    //vertical camera movement 
    if (ypos >= 0 && ypos < ResourceManager.ScrollWidth) 
    { 
     movement.z -= ResourceManager.ScrollSpeed; 
    } 
    else if (ypos <= Screen.height && ypos > (Screen.height - ResourceManager.ScrollWidth)) 
    { 
     movement.z += ResourceManager.ScrollSpeed; 
    } 

    //make sure movement is in the direction the camera is pointing 
    //but ignore the vertical tilt of the camera to get sensible scrolling 
    movement = Camera.main.transform.TransformDirection(movement); 
    //Up/down movement will be calculated diferently 
    movement.y = 0; 

但是,如果我這樣做,垂直運動不爲inital相機輪流工作,當我旋轉的攝像頭,運動發生在陌生的速度。

如何正確應用相機上的運動矢量?

回答

2

那麼,這裏的問題是TransformDirection將保留向量的長度。因此,如果您向下傾斜相機,則總長度會在y,x和z軸之間分佈。既然你簡單地消除了y部分,矢量將變得更短。相機傾斜的越多,其他兩個軸上的損失就越多。

通常只需旋轉單位矢量,然後按需要對其進行修改並在完成時對其進行標準化處理通常更容易。這個單位矢量然後可以通過你的實際運動矢量來縮放。類似的東西:

// [...] 
Vector3 forward = Camera.main.transform.forward; 
Vector3 right = Camera.main.transform.right; 
forward.y = 0f; 
right.y = 0f; // not needed unless your camera is also rotated around z 
movement = forward.normalized * movement.z + right.normalized * movement.x; 
// [...] 

另一種方法是分開你的兩個旋轉。所以通過使用一個空的遊戲對象,它只能圍繞y旋轉,並讓相機成爲該遊戲對象的一個​​子對象。現在相機只能繞着本地x軸旋轉,以您想要的方式傾斜。爲了將相機看起來朝不同的方向旋轉,你可以圍繞y旋轉空的遊戲對象。這樣,您可以使用空GameObject的變換來轉換方向,就像您在代碼中所做的那樣,因爲相機的傾斜並不重要。

+0

非常感謝你幫助我。最後一個微小的故障:如果我將相機*旋轉超過90°(所以它是「顛倒」),頂部/底部方向是顛倒的。我將通過將角度限制爲最大值來修復它。 – 2014-11-03 22:52:49