直接上代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class Drag : MonoBehaviour,IDragHandler
{
public void OnDrag(PointerEventData eventData)
{
Vector3 screenPos = Camera.main.WorldToScreenPoint(transform.position);
Vector3 mouseScreenPos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPos.z);
transform.position = Camera.main.ScreenToWorldPoint(mouseScreenPos);
}
}
今天不知道咋回事附不上图片
首先我写给大家说下 关于IDragHandler这个接口是什么意思根据我们的标题可以出我们今天写的是3d物体拖拽,所以说IDragHandler它就是拖拽中,当然既然有拖拽中就一定有开始拖拽
开始拖拽 IBeginDragHandler 拖拽结束IEndDragHandler 它们用途也相当广泛比如我们常见的背包拖拽这是我们就需要它们来 但是今天我们就讲3D物体拖拽
首先我们需要获取3d物体在屏幕坐标的z轴所以我们这边就用了主相机一个方法,Camera.main.WorldToScreenPoint 这个就是将世界转为屏幕坐标
接着我们得到了3d物体在屏幕坐标的z轴后我们需要将鼠标的z坐标替换成我们刚刚得到的3d物体在屏幕坐标的z轴
最后我们只需要把我们得到的新坐标从屏幕转成世界Camera.main.ScreenToWorldPoint
赋给3d物体就可以;
注意 我们在用3d物体拖拽是需要添加2个组件 一个是相机的 Physics Raycaster 另一个就是
EventSystem