KYJxierang/Assets/Scripts/UI/UIDragToScene3D.cs
2024-12-22 23:07:46 +08:00

71 lines
2.0 KiB
C#

using UnityEngine;
using UnityEngine.EventSystems;
public class UIDragToScene3D : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
public GameObject buildingPrefab; // 对应的建筑预制件
private GameObject previewObject; // 拖动时显示的建筑物(实际的 3D 模型)
/// <summary>
/// 开始拖动时
/// </summary>
/// <param name="eventData"></param>
public void OnBeginDrag(PointerEventData eventData)
{
Debug.Log("Drag Started");
// 创建一个 3D 物体作为拖动中的预览对象
if (buildingPrefab != null)
{
previewObject = Instantiate(buildingPrefab);
previewObject.GetComponent<Collider>().enabled = false; // 禁用碰撞体,避免干扰物理检测
}
}
// 拖动中
public void OnDrag(PointerEventData eventData)
{
if (previewObject != null)
{
// 获取鼠标的世界坐标
Vector3 mouseWorldPosition = GetMouseWorldPosition();
previewObject.transform.position = mouseWorldPosition; // 更新预览对象的位置
}
}
/// <summary>
/// 拖动结束时
/// </summary>
/// <param name="eventData"></param>
public void OnEndDrag(PointerEventData eventData)
{
Debug.Log("Drag Ended");
if (previewObject != null)
{
// 在拖动结束时将预览对象转为实际的建筑物
previewObject.GetComponent<Collider>().enabled = true; // 恢复碰撞体
previewObject = null; // 清空预览对象
}
}
/// <summary>
/// 获取鼠标的世界坐标
/// </summary>
/// <returns></returns>
private Vector3 GetMouseWorldPosition()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out RaycastHit hit, Mathf.Infinity))
{
// 如果射线命中地面,返回命中的点
return hit.point;
}
else
{
// 如果没有命中地面,返回一个默认点
return ray.GetPoint(10); // 默认距离相机 10 个单位
}
}
}