2014-07-18 36 views
1

我在Unity中創建了自己的角色,現在我正在使用相機,並且想要正確操作相機的Y旋轉角度。Mathf.clamp無法正常工作

mouseRotY = Mathf.Clamp(mouseRotY, -90.0f, 90.0f); 

那麼恰好是將相機從359到0沒什麼旋轉反應,直到我玩遊戲的時候將我的鼠標了。它使屏幕看起來像閃爍。

這裏是我的全碼:

using UnityEngine; 
using System.Collections; 

public class FirstPersonController : MonoBehaviour { 

    CharacterController cc; 

    public float baseSpeed = 3.0f; 
    public float mouseSensitivity = 1.0f; 

    float mouseRotX = 0, 
      mouseRotY = 0; 

    public bool inverted = false; 

    float curSpeed = 3.0f; 

    string h = "Horizontal"; 
    string v = "Vertical"; 

    void Start() { 
     cc = gameObject.GetComponent<CharacterController>(); 
    } 

    void FixedUpdate() { 

     curSpeed = baseSpeed; 

     mouseRotX = Input.GetAxis("Mouse X") * mouseSensitivity; 
     mouseRotY -= Input.GetAxis("Mouse Y") * mouseSensitivity;; 
     mouseRotY = Mathf.Clamp(mouseRotY, -90.0f, 90.0f); 
     if (!inverted) 
      mouseRotY *= -1; 
     else 
      mouseRotY *= 1; 

     float forwardMovement = Input.GetAxis(v); 
     float strafeMovement = Input.GetAxis(h); 

     Vector3 speed = new Vector3(strafeMovement * curSpeed, 0, forwardMovement * curSpeed); 
     speed = transform.rotation * speed; 



     cc.SimpleMove(speed); 
     transform.Rotate(0, mouseRotX, 0); 
     Camera.main.transform.localRotation = Quaternion.Euler(mouseRotY, 0 ,0); 

    } 
} 

如果有人對你能幫我這一點,那將是輝煌的。謝謝。

回答

0

你的倒置邏輯是有缺陷的,只是把它拿出來,它的工作原理。要反轉旋轉,你只需要在每一幀只反轉輸入,而不是旋轉本身(它會從+到 - 再次回到+等等)。下面是Y型旋轉倒置標誌工作的精簡版:

using UnityEngine; 
using System.Collections; 

public class FirstPersonController : MonoBehaviour 
{ 
    public float mouseSensitivity = 1.0f; 

    float mouseRotY = 0.0f; 

    public bool inverted = false; 
    private float invertedCorrection = 1.0f; 

    void FixedUpdate() 
    { 
     if(Input.GetAxis ("Fire1") > 0.0f) 
      inverted = !inverted; 

     if(inverted) 
      invertedCorrection = -1.0f; 
     else 
      invertedCorrection = 1.0f; 

     mouseRotY -= invertedCorrection * Input.GetAxis("Mouse Y") * mouseSensitivity; 

     mouseRotY = Mathf.Clamp(mouseRotY, -90.0f, 90.0f); 

     Camera.main.transform.localRotation = Quaternion.Euler(mouseRotY, 0.0f, 0.0f); 
    } 
} 

你可能想要做的另一件事是讓相機在你開始()的函數的原始旋轉。它現在的方式是在第一幀將旋轉設置爲零。我不能從劇本中得知這是否是預期的行爲。