简体   繁体   中英

How can I limit the rotation on the Y axis so that the player can't continuously spin the camera in Unity

I have an upcoming project that I have to present on Monday and this is the last bug I have to resolve. It would be nice if someone could help me out, and could teach me how to apply an axis limiter, thanks in advance everyone.

The issue is that the camera can spin 360 degrees

Below is my current code that controls the camera

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);
}

Adding logical clamping to this makes it quite a bit clearer to read through, this method clamps the vertical rotation between 60 and -60 degrees, the comments should help in modifying it if you need

I ended up jumping into Unity to test it this time, instead of going off the top of my head

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);
}

Goodluck with the project

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM