2016-11-04 185 views
0

我在Unity中創建3D遊戲,我有一個腳本可以讓玩家用鼠標四處看。爲了讓玩家朝着他們所看的方向移動,我正在使用transform.forward。我的問題是,當他們看着天花板並按'W'(向前)時,它們開始升起。基本上我需要知道是否有一種方法或子方法transform.forward只允許在x和z軸上移動。在Unity中預防Y軸移動`transform.forward`

這裏是我運動腳本(C#):

if (transform.rotation.x < -10) 
     { 
      //do no forward or backward movement 
      Debug.Log("Rotation too great to forward move..."); 
      tooGoodForMovement = true; 

     } 
     else 
     { 
      tooGoodForMovement = false; 
      if (Input.GetKey(KeyCode.W)) 
      { 
       //Forward 
       player.velocity = (transform.FindChild("Main Camera").transform.forward * moveSpeed); 
      } 
      if (Input.GetKey(KeyCode.S)) 
      { 
       //Back 
       player.velocity = (-transform.FindChild("Main Camera").transform.forward * moveSpeed); 
      } 
     } 
     if (Input.GetKey(KeyCode.A)) 
     { 
      //Left 
      player.velocity = -transform.FindChild("Main Camera").transform.right * moveSpeed; 
     } 

     if (Input.GetKey(KeyCode.D)) 
     { 
      //Right 
      player.velocity = transform.FindChild("Main Camera").transform.right * moveSpeed; 
     } 

回答

2

嘗試設置你的速度矢量到一個臨時變量,並重新在Y爲零。

Transform camera; 

void Start() 
{ 
    //Cache transform.FindChild so that we don't have to do it every time 
    camera = transform.FindChild("Main Camera"); 
} 

然後在您的其他功能:

Vector3 velocity = Vector3.zero; 

if (transform.rotation.x < -10) 
{ 
    //do no forward or backward movement 
    Debug.Log("Rotation too great to forward move..."); 
    tooGoodForMovement = true; 
} 
else 
{ 
    tooGoodForMovement = false; 
    if (Input.GetKey(KeyCode.W)) 
    { 
     //Forward 
     velocity = camera.forward * moveSpeed; 
    } 
    if (Input.GetKey(KeyCode.S)) 
    { 
     //Back 
     velocity = -camera.forward * moveSpeed; 
    } 
} 
if (Input.GetKey(KeyCode.A)) 
{ 
    //Left 
    velocity = -camera.right * moveSpeed; 
} 

if (Input.GetKey(KeyCode.D)) 
{ 
    //Right 
    velocity = camera.right * moveSpeed; 
} 

velocity.Y = 0; 
player.velocity = velocity; 
+1

這是確定。請爲每次完成的FindChild(「主攝像機」)添加一個修復程序。這很好。 – Programmer

+0

這工作。謝謝!我應該早點想到它。另外@Programmer,你修理FindChild(「主攝像頭」)是什麼意思? –

+0

@ Sub6Resources檢查更新的答案。使用'FindChild'永遠是昂貴的。緩存變換。 – Programmer