public class DragTarget : MonoBehaviour {
//防止鼠标按下开始拖拽时,物体移动,需要计算偏移量
Vector3 offset;
private void OnMouseDown()
{
Vector3 objSreen = Camera.main.WorldToScreenPoint(transform.position);
//物体距相机的距离,需要用到objSreen.z,移动时不改变Z值
Vector3 mouseSreen = new Vector3(Input.mousePosition.x, Input.mousePosition.y, objSreen.z);
offset = objSreen - mouseSreen;
}
private void OnMouseDrag()
{
Vector3 objSreen = Camera.main.WorldToScreenPoint(transform.position);
//物体距相机的距离,需要用到objSreen.z,移动时不改变Z值
Vector3 mousePosition = new Vector3(Input.mousePosition.x, Input.mousePosition.y, objSreen.z);
Vector3 objPostion = Camera.main.ScreenToWorldPoint(mousePosition+offset);
transform.position = objPostion;
}
}