unity拖拽drag_Unity3D UGUI , 3D物体 拖拽跟随鼠标

不使用射线实现 拖拽物体以及UGUI

主要函数为拖拽UGUI主要函数   RectTransformUtility.ScreenPointToWorldPointInRectangle

拖拽具有碰撞体,物体的主要函数   Camera.main.ScreenToWorldPoint

第二个函数一般可以把 Input.mousePosition当作参数传给 ScreenToWorldPoint(Input.mousePosition)

然后我们再把结果给我们想要拖动的物体 的 Position,如果摄像机的Projection 是 Orthographic(正交)问题会少点,可摄像机模式是Perspective(透视)就完全没法用了

Input.mousePosition 的Z 是重点 传给ScreenToWorldPoint的时候z需要是摄像机与物体所在平面的距离 是图中摄像机与黑色面的距离 紫色Cube是被拖拽物体 (黑色面是假象面)

求这个距离只需使用矢量投影便可轻松求值 ("矢量投影"说明图片 在末尾)

image.png

UGUI拖拽代码         与拖拽有关的函数只有一个OnDrag()using UnityEngine;using UnityEngine.EventSystems;using UnityEngine.UI;public class UGUIDrag : MonoBehaviour,IDragHandler {

Image _image;

RectTransform _rectTransform;    private void Awake()

{

_image = GetComponent();

_rectTransform = GetComponent();

}    public void OnDrag(PointerEventData eventData)

{

Vector3 globalMousePos;        if (RectTransformUtility.ScreenPointToWorldPointInRectangle(_rectTransform, eventData.position, eventData.pressEventCamera, out globalMousePos))

{

_rectTransform.position = globalMousePos;

}

}

}

带有3D/2D碰撞体的物体拖拽using UnityEngine;public class ScreenToWorldTest : MonoBehaviour

{    private Camera _currentCamera;    private Transform _target;    private void Awake()

{

_currentCamera = Camera.main;

_target = transform;

}

private void OnMouseDrag()

{        //得到摄像机到物体的向量

Vector3 CO_Direction = _target.position - _currentCamera.transform.position;        //得到摄像机与物体所在平面的距离

float cPlane = Vector3.Dot(CO_Direction, _currentCamera.transform.forward);

_target.position = _currentCamera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, cPlane));

}

}

矢量投影

作者:L罗夏

链接:https://www.jianshu.com/p/1b66f0b707bf

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值