簡體   English   中英

在Unity中夾緊垂直旋轉

[英]clamping a vertical rotation in Unity

我開始了FPS項目。 我有一個膠囊作為播放器,頭上有一個空的GO,相機是頭的子對象。

在垂直軸上,我將y旋轉限制為-70(最小)和70(最大)。 令人驚訝的是,該值沒有被鉗位。

    [SerializeField]
    private Transform playerHead;

    float inputHorizontal;
    float inputVertical; 

    float sensitivity = 50;

    float yMin = -70;
    float yMax = 70;

    Vector2 direction; // movement direction

Transform playerTransform;

void Start()
{
playerTransform = GameObject.FindGameObjectWithTag("Player").transform;
}

    private void Update()
    {
        inputHorizontal = Input.GetAxisRaw("Mouse X");
        inputVertical = -Input.GetAxisRaw("Mouse Y"); // Inverted Input!

        direction = new Vector2(
                inputHorizontal * sensitivity * Time.deltaTime,
                Mathf.Clamp(inputVertical * sensitivity * Time.deltaTime, yMin, yMax)); // The horizontal movement and the clamped vertical movement

        playerTransform.Rotate(0, direction.x, 0);
        playerHead.Rotate(direction.y, 0, 0);
    }

價值

direction.y

被夾住,但我仍然可以繞頭轉動360度。

您正在夾緊增量旋轉-而不是實際旋轉。 換句話說, direction不是最終的旋轉,而是旋轉的變化。 您正在有效地做的是將旋轉限制為每幀70度。

您可能想限制playerHead的實際旋轉,例如通過在更新結束時添加以下幾行:

Vector3 playerHeadEulerAngles = playerHead.rotation.eulerAngles;
playerHeadEulerAngles.y = Mathf.Clamp(playerHeadEulerAngles.y, yMin, yMax);
playerHead.rotation = Quaternion.Euler(playerHeadEulerAngles);

無論如何,當您分別使用每個組件時,也沒有理由創建方向矢量。

夾緊最終的Y方向值而不是當前的鼠標移動-

[SerializeField]
private Transform playerHead;

float inputHorizontal;
float inputVertical; 

float sensitivity = 50;

float yMin = -70;
float yMax = 70;

Vector2 direction; // movement direction
float currYDir = 0,prevYDir = 0;

Transform playerTransform;

void Start()
{
playerTransform = GameObject.FindGameObjectWithTag("Player").transform;
}

private void Update()
{
    inputHorizontal = Input.GetAxisRaw("Mouse X");
    inputVertical = -Input.GetAxisRaw("Mouse Y"); // Inverted Input!

    direction = new Vector2(
            inputHorizontal * sensitivity * Time.deltaTime,
            inputVertical * sensitivity * Time.deltaTime); // The horizontal movement and the clamped vertical movement

    playerTransform.Rotate(0, direction.x, 0);

    currYDir = prevYDir + direction.y;
    currYDir = Mathf.Clamp(currYDir, yMin, yMax);
    playerHead.Rotate(currYDir-prevYDir, 0, 0);

    prevYDir = currYDir;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM