How to constrain rotation from mouse input in unity 5?

狂风中的少年 提交于 2019-12-11 03:05:37

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/32792490/how-to-constrain-rotation-from-mouse-input-in-unity-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!