簡體   English   中英

如何在 Unity3d ZD7EFA19FBE7D3972FD5ADB6024223D74?

[英]How to Set object rotation limits around a pivot in Unity3d C#?

我正在開發一個曲折游戲,如下所示:[1]: https://i.stack.imgur.com/miKmH.jpg [ZigZagGame][1]。

目標是讓球沿着路徑 (ZigZag) 傳遞,通過圍繞 pivot 旋轉路徑(上、下、左和右),我使用鼠標拖動將 pivot 放在 ZigZag 的另一端。 我想限制路徑的方向。 這是我要實現的代碼:`

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RotationCheminOnDragMouse : MonoBehaviour
{
  float speed = 1.2f;

private void OnMouseDrag()
  {
      float rotx = Input.GetAxis("Mouse X") * speed * Mathf.Deg2Rad;
      float roty = Input.GetAxis("Mouse Y") * speed * Mathf.Deg2Rad;

      Vector3 backAngle = Vector3.back;
      Vector3 leftAngle = Vector3.left;

      transform.RotateAround(backAngle, -rotx);
      transform.RotateAround(leftAngle, roty);

  }

  private void Update()
  {
      if (Input.GetMouseButtonDown(0))
      {
          OnMouseDrag();
      }

  }


}

` 那么我該如何設置這些限制呢? 知道我不明白如何管理 C # 中的統一角度。 我希望你能幫我解決這個問題。 並提前感謝您的任何回復。

您可能正在使用 Mathf.Clamp,或者 Mathf.Clamp 僅用於此目的,以限制旋轉。

您應該跟蹤您已經旋轉了多少,然后限制新的旋轉,例如

public class RotationCheminOnDragMouse : MonoBehaviour
{
    float speed = 1.2f;

    [SerializeField] float minY = -45;
    [SerializeField] float maxY = 45;
    [SerializeField] float minX = -45;
    [SerializeField] float maxX = 45;

    private Vector2 alreadyRotated;

    private void OnMouseDrag()
    {
        var rotx = Input.GetAxis("Mouse X") * speed * Mathf.Deg2Rad;
        var roty = Input.GetAxis("Mouse Y") * speed * Mathf.Deg2Rad;

        // Now here you limit how much you can rotate
        if(rotX < 0)
        {
            rotx = Mathf.Max(rotx, minX - alreadyRotated.x));
        }
        else if(rotX > 0)
        {
            rotx = Maths.Min(rotx, maxX - alreadyRotated.x));
        }

        if(rotY < 0)
        {
            roty = Mathf.Max(roty, minY - alreadyRotated.y));
        }
        else if(rotY > 0)
        {
            roty = Maths.Min(roty, maxY - alreadyRotated.y));
        }

        transform.RotateAround(Vector3.forward, rotx);
        transform.RotateAround(Vector3.left, roty);

        alreadyRotated += new Vector2 (rotX, rotY);
    }

    private void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            OnMouseDrag();
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM