旋转对象打破限制/界限

时间:2016-04-19 22:03:15

标签: c# unity3d rotation unity5

我目前使用以下逻辑围绕另一个对象旋转对象,并将条件设置为不超过90度或低于1.

protected void RotationBounds(){
 bRotateDown = true;
 bRotateUp = true;
 if (_CannonTube.transform.rotation.eulerAngles.z >= 90)
     bRotateUp = false;
 if (_CannonTube.transform.rotation.eulerAngles.z <= 1)
     bRotateDown = false;
 }

一旦条件被击中,这允许我停止一个方向的旋转。然后我使用以下鼠标移动控件应用旋转:

protected void RotateCannonMouse(){
if (Input.GetKey ("mouse 0")) {
        if (Input.GetAxis ("Mouse Y") > 0 && bRotateUp == true && bRotateDown == true 
         || Input.GetAxis ("Mouse Y") > 0 && bRotateUp == false && bRotateDown == true) {
                    transform.RotateAround (_SphereBase.position, -transform.forward,
                    Input.GetAxis ("Mouse Y") * 15);
           }
         if (Input.GetAxis ("Mouse Y") < 0  && bRotateUp == true && bRotateDown == true
         || Input.GetAxis ("Mouse Y") < 0  && bRotateUp == true && bRotateDown == false) {
                     transform.RotateAround (_SphereBase.position, -transform.forward,
                      Input.GetAxis ("Mouse Y") * 15);
       }
}

然后在更新方法中调用以下功能。

  void Update () {
    RotateCannonMouse();
    RotationBounds();
  }

我的问题/问题是,如果我以慢/中速旋转物体,则条件会达到,并且它会像我期望的那样。如果我快速旋转物体,它将突破条件并弄乱旋转。以前有人遇到过这个问题吗?我想也许更新方法没有足够快地迭代,或者我正在快速旋转对象,它会跳过边界值?

先谢谢

2 个答案:

答案 0 :(得分:1)

收集所有数据,进行所有计算和检查,然后在必要时最后轮换。你这样做有点倒退。你首先旋转,然后尝试清理混乱。你确定可以使它发挥作用,但它是无条件或无益的最难的方式。

只存储Input.GetAxis("Mouse Y")的返回值,将其添加到计算的(甚至也存储的)当前旋转中,检查它是否在边界内(或夹住它)然后在最后确定是否你旋转多远。

(你也不需要做一个布尔值==,无论是真还是假 - &gt; if(abool == true)if(abool)相同而if(abool == false)与{相同} {1}}。ofc它不是错误,只是让它难以阅读)

答案 1 :(得分:1)

这是我们找到的解决方案

//If mouse has been clicked
    if (Input.GetKey ("mouse 0")) {

        //Get the angle the mouse wants to move by
        float mouseY = Input.GetAxis ("Mouse Y") * 5;

        //If the angle is not 0 then we see how much it can move by
        if (mouseY != 0) {

            //Get the current angle of the cannon
            float currentAngle = _CannonTube.transform.rotation.eulerAngles.z;

            //Work out the new angle that the cannon will go to
            float calcAngle = 0.0f;

            if (mouseY < 0) {
                calcAngle = currentAngle - mouseY;
            } else {
                calcAngle = currentAngle - mouseY;
            }

            //Clamp calcAngle between 5 and 85 
            var newAngle = Mathf.Clamp (calcAngle, 5, 85);

            //calcualte the angle that we are allowed to move by.
            //for example if current angle is 85 and new angle is 85 from the clamp then we move 0 degrees
            var rotateAngle = currentAngle - newAngle;

            //rotate the cannon
            transform.RotateAround (_SphereBase.position, -transform.forward, rotateAngle);
        }
    }