给需要添加的物体添加标签,添加碰撞器 完事!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class drag : 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))
{
Debug.DrawLine(ray.origin, hitInfo.point);
if (hitInfo.collider.tag=="drag")
{
go = hitInfo.collider.gameObject;
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.transform.position = currentPosition;
}
isDrage = true;
}
else
{
isDrage = false;
}
}
}
|