You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
34 lines
1.4 KiB
34 lines
1.4 KiB
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;//这个很重要,循环执行 |
|
|
|
} |
|
} |
|
|
|
} |
|
|
|
} |
|
|
|
|