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

作者: 杰罗xr | 来源:发表于2018-08-07 19:10 被阅读75次

不使用射线实现 拖拽物体以及UGUI
主要函数为
UGUI RectTransformUtility.ScreenPointToWorldPointInRectangle
碰撞体物体 Camera.main.ScreenToWorldPoint

第二个函数一般可以把 Input.mousePosition当作参数传给 ScreenToWorldPoint(Input.mousePosition)
然后我们再把结果给我们想要拖动的物体 的 Position,如果摄像机的Projection 是 Orthographic(正交)问题会少点,可摄像机模式是Perspective(透视)就完全没法用了

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

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

image.png

UGUI拖拽代码 与拖拽有关的函数只有一个OnDrag()

using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class UGUIDrag : MonoBehaviour,IDragHandler,IDropHandler,IBeginDragHandler,IEndDragHandler {

    Image _image;
    RectTransform _rectTransform;

    private void Awake()
    {
        _image = GetComponent<Image>();
        _rectTransform = GetComponent<RectTransform>();
    }


    public void OnBeginDrag(PointerEventData eventData)
    {
        _image.raycastTarget = false;
        transform.SetAsLastSibling();
    }

    public void OnDrag(PointerEventData eventData)
    {
        Vector3 globalMousePos;
        if (RectTransformUtility.ScreenPointToWorldPointInRectangle(_rectTransform, eventData.position, eventData.pressEventCamera, out globalMousePos))
        {
            _rectTransform.position = globalMousePos;
        }
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        _image.raycastTarget = true;
    }

    public void OnDrop(PointerEventData eventData)
    {
        Debug.Log(gameObject.name + "OnDrop");
    }

}

带有3D碰撞体的物体拖拽

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));
    }

}

矢量投影

相关文章

网友评论

  • Joe_Game:这本书是什么书,我比较好奇。
    Joe_Game:@L罗夏 哦哦,那本是叶劲峰翻译过来的,可以的。
    杰罗xr:@Joe_Game 游戏引擎架构
  • Clean_1306:好东西,mark下
  • 272d4bc6083b:感谢作者
    杰罗xr:@别忘了给我打电话 哈哈哈 第一个评论我的人:v:

本文标题:Unity3D UGUI , 3D物体 拖拽跟随鼠标

本文链接:https://www.haomeiwen.com/subject/qwpgvftx.html