将MoveWithMouse代码挂载到脚本上,就可以实现物体的移动
using System.Collections;
using QFramework;
using UnityEngine;
public class MoveWithMouse : MonoBehaviour
{
public bool beSleceted = false;
private Vector3 dragOffset; // 拖拽偏移量
public float dragSpeed = 2f;
public float zOffset = 10f; // 物体与相机的深度偏移
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
}
// Update is called once per frame
void Update()
{
//text();
HandleObjectInteraction();
}
/// <summary>
/// 处理鼠标点中
/// </summary>
private void HandleObjectInteraction()
{
// 鼠标按下瞬间
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
Debug.Log($"被点的物体为:{hit.collider.gameObject.name}");
if (hit.collider.transform.parent)
{
Debug.Log($"被点物体的父物体为:{hit.collider.transform.parent.name}");
}
// 如果点中的是自己
if (hit.collider.transform == this.transform)
{
Debug.Log("武器被选中了");
// 选中并准备拖拽
beSleceted = true;
UpdateDragOffset();
}
}
}else if(Input.GetMouseButtonUp(0)&&beSleceted == true)
{
beSleceted = false;
}
// 持续拖拽状态
if (beSleceted == true && Input.GetMouseButton(0))
{
// 动态更新偏移量(处理物体移动中的位置变化)
UpdateDragOffset();
// 执行拖拽移动
DragSelectedObject();
}
}
// 动态计算偏移量(每次拖拽都更新)
private void UpdateDragOffset()
{
if (!beSleceted) return;
// 获取当前鼠标位置(深度使用物体当前位置的Z)
Vector3 mouseWorldPos = GetMouseWorldPositionForObject(this.gameObject);
// 计算当前偏移量
dragOffset = mouseWorldPos-this.gameObject.transform.position;
}
// 带深度校正的鼠标位置获取
private Vector3 GetMouseWorldPositionForObject(GameObject obj)
{
Vector3 screenPos = Camera.main.WorldToScreenPoint(obj.transform.position);
Vector3 mousePos = Input.mousePosition;
mousePos.z = screenPos.z; // 保持相同的Z深度
return Camera.main.ScreenToWorldPoint(mousePos);
}
// 拖拽移动逻辑
private void DragSelectedObject()
{
if (beSleceted)
{
Vector3 targetPosition = this.transform.position + dragOffset;
// 直接移动
this.gameObject.transform.position = Vector3.Lerp(
this.gameObject.transform.position,
targetPosition,
Time.deltaTime * dragSpeed
);
}
}
}