亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

Unity3D UGUI , 3D物體 拖拽跟隨鼠標

標簽:
Unity 3D

不使用射线实现 拖拽物体以及UGUI
主要函数为

  • 拖拽UGUI主要函数   RectTransformUtility.ScreenPointToWorldPointInRectangle

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

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

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

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

700

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<Image>();
        _rectTransform = GetComponent<RectTransform>();
    }    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));
    }

}

700

矢量投影



作者:L罗夏
链接:https://www.jianshu.com/p/1b66f0b707bf

點擊查看更多內容
TA 點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
  • 推薦
  • 評論
  • 收藏
  • 共同學習,寫下你的評論
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消