简体   繁体   中英

How to constrain rotation from mouse input in unity 5?

I have a very basic script to move the camera from the mouse position, but I want to constrain the rotation of the z axis to some values. With the code below it all works fine, but the camera can be rotated fully on the z axis, I want to limit it to 20 and -40. I have tried to use mathf.clamp but that didn't work and when printed to the console it only printed out the right most value in the mathf.clamp. I also tried using an if statement to see if the rotation was over the limit, and then to reset it if it was. But neither worked... I have also looked around on Unity answers but I don't understand any of the other answers, could someone show me how to do it?

Code:

void Update () {
        transform.rotation = Quaternion.Euler(0f, Input.mousePosition.x, Input.mousePosition.y);
    }

This is how you clamp it.

void Update()
{
    float zRotation = Mathf.Clamp(Input.mousePosition.y, -40, 20);
    transform.rotation = Quaternion.Euler(0f, Input.mousePosition.x, zRotation);
}

But I don't think it does what you want. The mouse position is given in window coordinates, so you won't ever have negative values. You'll probably want to translate the coordinates first, like this:

void Update()
{
    float yRotation = (Input.mousePosition.x - Screen.width / 2) * 360 / Screen.width;
    float zRotation = (Input.mousePosition.y - Screen.height / 2) * 180 / Screen.height;
    zRotation = Mathf.Clamp(zRotation, -40, 20);
    transform.rotation = Quaternion.Euler(0f, yRotation, zRotation);
}

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