如何限制单位5中鼠标输入的旋转? [英] How to constrain rotation from mouse input in unity 5?

查看:97
本文介绍了如何限制单位5中鼠标输入的旋转?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常基本的脚本,可以将相机从鼠标位置移开,但是我想将z轴的旋转限制为某些值.使用下面的代码,一切正常,但是相机可以在z轴上完全旋转,我想将其限制为20和-40.我试过使用mathf.clamp,但是没有用,当打印到控制台时,它只打印出mathf.clamp中最正确的值.我还尝试使用if语句查看旋转是否超出限制,然后将其重置.但是都没有用...我也浏览了Unity的答案,但是我不明白其他任何答案,有人可以教我如何做吗?

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?

代码:

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

这篇关于如何限制单位5中鼠标输入的旋转?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆