限制相机旋转角度

时间:2016-05-07 13:54:13

标签: c# unity3d

我希望能够在某个点之后限制相机旋转,并且只能在某个区域旋转,这是到目前为止的代码......

void Update() {
    float mouseX = Input.GetAxis("Mouse X");
    float mouseY = -Input.GetAxis("Mouse Y");

    rotY += mouseX * mouseSensitivity * Time.deltaTime;
    rotX += mouseY * mouseSensitivity * Time.deltaTime;

    desiredy = Camera.main.transform.eulerAngles.y;
    desiredx = Camera.main.transform.eulerAngles.x;

    if (!(desiredy < maxy && desiredy > miny))
    {
        //i dont know what to put in here, i have tried everything
    }


    else if (!(desiredx < maxx && desiredx > minx))
    {
         //i dont know what to put in here, i have tried everything
    }

    else
    {
        localRotation = Quaternion.Euler(rotX, rotY, 0.0f);
        transform.rotation = localRotation;
    }
}

1 个答案:

答案 0 :(得分:4)

你正在使你的不必要的逻辑复杂化。您只需要Mathf.Clamp函数,以确保您的值在指定范围内。

void Update()
{
    rotateCamera();
}


public float xSensitivity = 100.0f;
public float ySensitivity = 100.0f;

public float yMinLimit = -45.0f;
public float yMaxLimit = 45.0f;

public float xMinLimit = -360.0f;
public float xMaxLimit = 360.0f;

float yRot = 0.0f;
float xRot = 0.0f;

void rotateCamera()
{
    xRot += Input.GetAxis("Mouse X") * xSensitivity * Time.deltaTime;
    yRot += Input.GetAxis("Mouse Y") * ySensitivity * Time.deltaTime;
    yRot = Mathf.Clamp(yRot, yMinLimit, yMaxLimit);
    Camera.main.transform.localEulerAngles = new Vector3(-yRot, xRot, 0);

}