首页 > 解决方案 > 如何限制 Y 轴上的旋转,以使玩家无法在 Unity 中连续旋转相机

问题描述

我有一个即将到来的项目,我必须在周一展示,这是我必须解决的最后一个错误。如果有人可以帮助我,并且可以教我如何应用轴限制器,那就太好了,在此先感谢大家。

问题是相机可以旋转360度

下面是我当前控制相机的代码

public float sensitivity = 30.0f;
private GameObject cam;
float rotX, rotY;

private void Start()
{
    sensitivity = sensitivity * 1.5f;
    Cursor.visible = false; // For convenience
}

private void Update()
{
    rotX = Input.GetAxis("Mouse X") * sensitivity;
    rotY = Input.GetAxis("Mouse Y") * sensitivity;
    //Apply rotations
    CameraRotation(cam, rotX, rotY);
}

private void CameraRotation(GameObject cam, float rotX, float rotY)
{
    //Rotate the player horizontally
    transform.Rotate(0, rotX * Time.deltaTime, 0);
    //Rotate the players view vertically
    cam.transform.Rotate(-rotY * Time.deltaTime, 0, 0);
}

标签: c#visual-studiounity3d

解决方案


添加逻辑钳位使其通读更加清晰,此方法将垂直旋转钳位在 60 到 -60 度之间,如果您需要,注释应该有助于修改它

这次我最终跳进了 Unity 来测试它,而不是一头雾水

void CameraRotation(GameObject cam, float rotX, float rotY)
{
    //Rotate the player horizontally
    transform.Rotate(0, rotX * Time.deltaTime, 0);
    //Rotate the players view vertically
    cam.transform.Rotate(-rotY * Time.deltaTime, 0, 0);

    //Grab current rotation in degrees
    Vector3 currentRot = cam.transform.localRotation.eulerAngles;
    //If (x-axis > (degreesUp*2) && x-axis < (360-degreesUp))
    if (currentRot.x > 120 && currentRot.x < 300) currentRot.x = 300;
    //else if (x-axis < (degreesDown*2) && x-axis > (degreesDown))
    else if (currentRot.x < 120 && currentRot.x > 60) currentRot.x = 60;
    //Set clamped rotation
    cam.transform.localRotation = Quaternion.Euler(currentRot);
}

项目顺利


推荐阅读