实现拖拽的方法:
通过创建一个X-Z平面 得到从屏幕发出的射线到当前X-Z平面的碰撞点 得到的位置作为起始位置和结束位置
当鼠标按下的时候 得到的是初始位置 当鼠标松开的时候 得到的是结束位置
得到两个位置的距离
再通过Vector.Lerp()函数和Update()函数来平衡每一帧的差异 进而实现滑动的效果。
代码示例:直接挂在Camera上即可
private Vector3 dragStartPos, dragCurrentPos;
private Vector3 newPos;
private void Start()
{
newPos = transform.position;
}
private void HandleCameraMove()
{
if (Input.GetMouseButtonDown(1))
{
Plane plane = new Plane(Vector3.up, Vector3.zero);
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
float distance;
if (plane.Raycast(ray, out distance))
{
dragStartPos = ray.GetPoint(distance);
}
}
if (Input.GetMouseButton(1))
{
Plane plane = new Plane(Vector3.up, Vector3.zero);
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
float distance;
if (plane.Raycast(ray, out distance))
{
//获取到这条射线到XZ平面上具体点的位子信息
dragCurrentPos = ray.GetPoint(distance);
Vector3 difference = dragStartPos - dragCurrentPos;
Debug.Log(difference);
newPos = transform.position + difference;
}
}
transform.position = Vector3.Lerp(transform.position, newPos, moveTime * Time.deltaTime);
}
关于Plane:
官方文档:
通过创建一个平面 来计算鼠标出的射线到XZ平面的具体位置
第一个参数是垂直于平面向上的单位向量 这样判断平面为XZ方向
这里传入的向量必须是归一化的向量 也就是Vector3.up
第二个参数是距离原始点位的距离 默认为0即可
关于这一行 可以控制相机移动的方向
Vector3 difference = dragStartPos - dragCurrentPos;
比如说让鼠标从右上向左下滑动
那么就让镜头从左上向右上滑动