【问题标题】:Rotate object with RotateAround and give it a limit使用 RotateAround 旋转对象并给它一个限制
【发布时间】:2019-04-01 11:58:57
【问题描述】:

我的场景中有一个对象可以通过鼠标滑动来旋转 (RotateAround)。我想给对象一些旋转限制,例如 X 轴的 -45 度和 45 度,所以当它的旋转变为 45 度时,它不能超过它。

所以我在我的脚本中尝试了 Mathf.Clamp 方法,如下所示,它在 Y 轴上工作正常,对象围绕他的 X 轴旋转并且没有超出 Y 限制.但是在 X 轴上,当对象的 Y 旋转达到 O 时,它会立即变为 30 度,并带有奇怪的旋转!你能告诉我的代码有什么问题吗?

轮换脚本:

float sensitivity = 10f;
Vector3 firstPressPos;
Vector3 secondPressPos;
float minRotationX = 45;
float maxRotationX = 100;
float minRotationY = 30;
float maxRotationY = 30;

void Update () {

    if (Input.GetMouseButtonDown(0))
    {
        //save began touch 2d point
        firstPressPos = new Vector3(Input.mousePosition.x, Input.mousePosition.y);
    }

    if (Input.GetMouseButton(0))
    {
        //save ended touch 2d point
        secondPressPos = new Vector3(Input.mousePosition.x, Input.mousePosition.y);

        if (firstPressPos != secondPressPos)
        {
            float RotX = Input.GetAxis("Mouse X") * sensitivity * Time.deltaTime;
            float RotY = Input.GetAxis("Mouse Y") * sensitivity * Time.deltaTime;
            transform.RotateAround(Vector3.up, RotX);
            transform.RotateAround(Vector3.right, -RotY);

            Vector3 angles = transform.eulerAngles;
            angles.x = Mathf.Clamp(angles.x, minRotationX, maxRotationX);
            angles.y = Mathf.Clamp(angles.y, -minRotationY, maxRotationY);
            angles.z = 0;
            transform.eulerAngles = angles;
        }

    }

}

【问题讨论】:

标签: c# unity3d


【解决方案1】:

在编辑器中,旋转值在 -180 到 180 之间,但在 transform.eulerAngles 中,它们实际上在 0 到 360 之间。

所以你需要在夹紧之前调整你的角度值。

if(angles.y > 180)
{
    angles.y -= 180f;
}

angles.y = Mathf.Clamp(angles.Y, minY, maxY);

【讨论】:

  • 是的,你是对的,它的 -30 和 30,但是我怎样才能使用这个代码呢?我应该在哪里调用angles.x?
  • @Taik y和z分量的代码是一样的。但是,您不能限制 x 的值,因此您使用 2 if 语句检查旋转是高于 +30 还是低于 -30 并分配其值。
  • 谢谢,它适用于直角,但对于左角则不行,当对象旋转小于 0 时,对象立即移动到 -30 度!并且对象变得固定,此时无法旋转!
  • @Taik 好的,让我尝试另一种解决方案。我真的必须这样做,所以如果它不起作用,请继续寻求帮助
  • 我找到了解决方案,它应该是 (angles.y
猜你喜欢
  • 2014-05-02
  • 1970-01-01
  • 1970-01-01
  • 2020-07-04
  • 1970-01-01
  • 2019-10-29
  • 1970-01-01
  • 2016-06-13
  • 1970-01-01
相关资源
最近更新 更多