在项目中需要实现鼠标拖拽物体移动,按照网上一些大佬的教程可以实现鼠标拖拽,但是在项目中需要保持被拖拽的物体时刻保持在地面以上,不然就会被地形掩盖,找不到物体了,于是将代码进行了修改。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ModelDrage : MonoBehaviour
{
private Camera cam;//发射射线的摄像机
private GameObject go;//射线碰撞的物体
public static string btnName;//射线碰撞物体的名字
private Vector3 screenSpace;
private Vector3 offset;
private bool isDrage = false;
void Start()
{
cam = Camera.main;
}
void Update()
{
//整体初始位置
Ray ray = cam.ScreenPointToRay(Input.mousePosition);
//从摄像机发出到点击坐标的射线
RaycastHit hitInfo;
if(isDrage ==false)
{
if (Physics.Raycast(ray, out hitInfo))
{
//划出射线,只有在scene视图中才能看到
Debug.DrawLine(ray.origin, hitInfo.point);
go = hitInfo.collider.gameObject;
//print(btnName);
screenSpace = cam.WorldToScreenPoint(go.transform.position);
offset = go.transform.position - cam.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenSpace.z));
//物体的名字
btnName = go.name;
//组件的名字
}
else
{
btnName = null;
}
}
if (Input.GetMouseButton(0))
{
Vector3 currentScreenSpace = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenSpace.z);
Vector3 currentPosition = cam.ScreenToWorldPoint(currentScreenSpace) + offset;
if(btnName !=null&&go.tag=="sunmao")
{
//保持被拖拽物体保持水平面以上
if (currentPosition.y > 0)
{
go.transform.position = currentPosition;
}
else
go.transform.position = new Vector3(currentPosition.x, 0, currentPosition.z);
}
isDrage = true;
}
else
{
isDrage = false;
}
}
}
参考的博文出处:添加链接描述