Unity 如何使用鼠标光标拖动刚体

要使用鼠标光标拖动 Rigidbodies,我们需要 create 一个脚本,该脚本将附加到相机并检测是否单击了任何 Rigidbody,如果是,它将初始化拖动运动。

Sharp Coder 视频播放器

SC_DragRigidbody.cs

using UnityEngine;

public class SC_DragRigidbody : MonoBehaviour
{
    public float forceAmount = 500;

    Rigidbody selectedRigidbody;
    Camera targetCamera;
    Vector3 originalScreenTargetPosition;
    Vector3 originalRigidbodyPos;
    float selectionDistance;

    // Start is called before the first frame update
    void Start()
    {
        targetCamera = GetComponent<Camera>();
    }

    void Update()
    {
        if (!targetCamera)
            return;

        if (Input.GetMouseButtonDown(0))
        {
            //Check if we are hovering over Rigidbody, if so, select it
            selectedRigidbody = GetRigidbodyFromMouseClick();
        }
        if (Input.GetMouseButtonUp(0) && selectedRigidbody)
        {
            //Release selected Rigidbody if there any
            selectedRigidbody = null;
        }
    }

    void FixedUpdate()
    {
        if (selectedRigidbody)
        {
            Vector3 mousePositionOffset = targetCamera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, selectionDistance)) - originalScreenTargetPosition;
            selectedRigidbody.velocity = (originalRigidbodyPos + mousePositionOffset - selectedRigidbody.transform.position) * forceAmount * Time.deltaTime;
        }
    }

    Rigidbody GetRigidbodyFromMouseClick()
    {
        RaycastHit hitInfo = new RaycastHit();
        Ray ray = targetCamera.ScreenPointToRay(Input.mousePosition);
        bool hit = Physics.Raycast(ray, out hitInfo);
        if (hit)
        {
            if (hitInfo.collider.gameObject.GetComponent<Rigidbody>())
            {
                selectionDistance = Vector3.Distance(ray.origin, hitInfo.point);
                originalScreenTargetPosition = targetCamera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, selectionDistance));
                originalRigidbodyPos = hitInfo.collider.transform.position;
                return hitInfo.collider.gameObject.GetComponent<Rigidbody>();
            }
        }

        return null;
    }
}

设置

  • SC_DragRigidbody 脚本附加到任何相机
  • 您要拖动的对象放在相机前面(确保您要拖动的对象附加了 Rigidbody 组件)。

现在您可以用鼠标光标拖动刚体!

推荐文章
使用 Unity 的 Rigidbody 组件
在 Unity 中添加弹跳球物理
在 Unity 中创建基于物理的赛车游戏
在 Unity 中实现 2D 抓钩
在 Unity 中创建旗帜模拟
在 Unity 游戏中实现采矿机制
如何检查 Rigidbody 播放器是否在 Unity 中接地