using UnityEngine; using System.Collections; using UnityEngine.EventSystems; public class DragObject : MonoBehaviour { public bool isDrag=true; private Vector3 realPosition; IEnumerator OnMouseDown() { if (isDrag) { Vector3 screenSpace = Camera.main.WorldToScreenPoint(transform.position);//三维物体坐标转屏幕坐标 //将鼠标屏幕坐标转为三维坐标,再算出物体位置与鼠标之间的距离 Vector3 offset = transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenSpace.z)); while (Input.GetMouseButton(0)) { Vector3 curScreenSpace = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenSpace.z); Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenSpace) + offset; realPosition = new Vector3(curPosition.x, transform.position.y, curPosition.z); if (Input.GetKey(KeyCode.LeftControl)) realPosition = new Vector3(transform.position.x, curPosition.y, transform.position.z); if (!EventSystem.current.IsPointerOverGameObject()) transform.position = realPosition; yield return 0;//这个很重要,循环执行 } } } }