【Unity】鼠标点击获取世界坐标位置:物体移动至鼠标点击的位置

需求说明

鼠标点击3D场景时,可以获取其所在的世界坐标;

鼠标点击3D物体时,可以获取该物体;

鼠标点击3D物体时,可以让玩家移动至该物体;

成果展示

Scene部分

关于仓库栏的设置,物体如何进入仓库内容【查看此篇

能够被获取的物体,必须需要是一个碰撞体,即绑定了碰撞体组件。

Mouse3D需要绑定对应的脚本。

脚本部分

public class Mouse3D : MonoBehaviour
{

    public static Mouse3D Instance { get; private set; }

    [SerializeField] private LayerMask mouseColliderLayerMask = new LayerMask();

    private void Awake()
    {
        Instance = this;
    }

    private void Update()
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(ray, out RaycastHit raycastHit, 999f, mouseColliderLayerMask))
        {
            transform.position = raycastHit.point;
        }
    }

    public static Vector3 GetMouseWorldPosition() => Instance.GetMouseWorldPosition_Instance();
    public static Transform GetClickedTransform() => Instance.GetClickedTransform_Instance();

    private Vector3 GetMouseWorldPosition_Instance()
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(ray, out RaycastHit raycastHit, 999f, mouseColliderLayerMask))
        {
            return raycastHit.point;
        }
        else
        {
            return Vector3.zero;
        }
    }

    private Transform GetClickedTransform_Instance() {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(ray, out RaycastHit raycastHit, 999f, mouseColliderLayerMask))
        {
            return raycastHit.collider.transform;
        }
        else
        {
            return null;
        }
    }

}

Player脚本中相关内容

private void Update()
{
    Vector3 inputDir = new Vector3(0, 0, 0);
    if (Input.GetKey(KeyCode.UpArrow)) inputDir.z += +1f;
    if (Input.GetKey(KeyCode.DownArrow)) inputDir.z += -1f;
    if (Input.GetKey(KeyCode.LeftArrow)) inputDir.x += -1f;
    if (Input.GetKey(KeyCode.RightArrow)) inputDir.x += +1f;


    Vector3 moveDir = transform.forward * inputDir.z + transform.right * inputDir.x;
    transform.position += moveDir * moveSpeed * Time.deltaTime;

    if (Input.GetMouseButtonUp(1)) {
        Debug.Log(Mouse3D.GetMouseWorldPosition());
        Transform t = Mouse3D.GetClickedTransform();
        if (t != null)
        {
            Debug.Log(t.name);
            Vector3 targetPosition = t.position;
            targetPosition.y = transform.position.y;
            transform.DOMove(targetPosition, 2);//移动使用了Dotween插件
        }
        else {
            Debug.Log("null");
        }

    }
}
posted @ 2024-11-15 11:35  Sitar  阅读(4)  评论(0编辑  收藏  举报