在Unity中夹紧垂直旋转

时间:2017-05-01 11:26:21

标签: c# unity3d

我开始了一个FPS项目。我有一个胶囊作为播放器,一个空的GO作为头部,相机是头部的子对象。

在垂直轴上,我将y旋转夹紧到-70(min)和70(max)。令人惊讶的是,这个价值并没有受到限制。

    [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度。

1 个答案:

答案 0 :(得分:2)

您正在夹紧三角形旋转 - 而不是实际旋转。 换句话说,direction不是最终轮换,而是轮换的变化。你有效地做了什么,将旋转限制在每帧70度。

您可能希望限制playerHead的实际轮播,例如在更新结束时添加以下行:

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

当您分别使用每个组件时,也没有理由创建方向向量。