unity3d 所有3个轴上的夹具旋转

eqqqjvef  于 2023-06-30  发布在  其他
关注(0)|答案(1)|浏览(205)

我在我的对象上使用刚体,并使用鼠标单击和拖动来旋转对象。如何在两个Angular 之间夹紧所有3个轴?

public Rigidbody rb;

public void Update () {
  if (Input.GetMouseButton (0)) {
    rotX = Input.GetAxis ("Mouse X") * strength;
    rotY = Input.GetAxis ("Mouse Y") * strength;

    if (Input.touchCount > 0) {
      rotX = Input.touches[0].deltaPosition.x;
      rotY = Input.touches[0].deltaPosition.y;
    }

    rb.AddTorque (rotY, -rotX, 0);
  }
}
bq9c1y66

bq9c1y661#

当然,有几种可能的解决方案。使用以下代码,您可以通过检查器调整游戏对象的最小/最大旋转。
在你的 Update 函数之后,在 LateUpdate 中,我们得到当前的旋转并最终钳制它。

[SerializeField] private Vector3 maxRotation; // maximum rotation values for each axis
[SerializeField] private Vector3 minRotation; // minimum rotation values for each axis

private void LateUpdate()
{
    // get the current rotation of the GameObject
    Vector3 currentRotation = transform.rotation.eulerAngles;

    // clamp the rotation values in each axis
    float clampedXRotation = Mathf.Clamp(currentRotation.x, minRotation.x, maxRotation.x);
    float clampedYRotation = Mathf.Clamp(currentRotation.y, minRotation.y, maxRotation.y);
    float clampedZRotation = Mathf.Clamp(currentRotation.z, minRotation.z, maxRotation.z);

    // create a new rotation based on the clamped values
    Quaternion clampedRotation = Quaternion.Euler(clampedXRotation, clampedYRotation, clampedZRotation);

    // apply the clamped rotation to the GameObject
    transform.rotation = clampedRotation;
}

相关问题