using System.Collections.Generic;
using UnityEngine;
public class Drag : MonoBehaviour
{
public Camera mainCamera;
private Vector3 offset2D;
private Vector3 mDeep;
Vector3 temp;
void Start()
{
mDeep = mainCamera.WorldToScreenPoint(transform.position);
print("mDeep:" + mDeep);
print(transform.position);
}
/*
* Vector3 mDeep= mainCamera.WorldToScreenPoint(target.transform.position)
* 参数是三维坐标系的参数
* mDeep 的 x 和 y 对应的是 target 在二维屏幕中的位置,z对应的是 target 与 mainCamera 之间的深度
*
* Vector3 result = mainCamera.ScreenToWorldPoint(Input.mousePosition + offset2D + new Vector3(0, 0, mDeep.z));
* 参数的 x 和 y 确定的是 在二维屏幕中的位置,z 代表的是深度
* 参数 mDeep.z 反映的其实是深度
* */
void OnMouseDown()
{
// 计算出在屏幕上的误差
temp = Vector3.zero;
temp = mainCamera.WorldToScreenPoint(transform.position);
offset2D = new Vector3(temp.x, temp.y, -0) - Input.mousePosition;
}
void OnMouseDrag()
{
// 记得加上深度
transform.position = mainCamera.ScreenToWorldPoint(Input.mousePosition + offset2D + new Vector3(0, 0, mDeep.z));
}
}
精简一下: