拖拽物体

一:UI元素 ——使用UI事件接口

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

public class Test : MonoBehaviour,IDragHandler
{
    private GameObject nowDrag_go;//当前拖拽的物体

    public void OnDrag(PointerEventData eventData)
    {
        FollowMouse(eventData);
    }

    private void FollowMouse(PointerEventData eventData)
    {
        Vector3 globalMousePos;
        if (RectTransformUtility.ScreenPointToWorldPointInRectangle(GameObject.Find("Canvas").transform as RectTransform, 
            eventData.position, eventData.pressEventCamera, out globalMousePos))
        {
            nowDrag_go.transform.position = globalMousePos;
        }
    }
}

二:2D/3D物体——使用生命周期函数

using System;
using UnityEngine;

public class Test : MonoBehaviour
{
    private void OnMouseDrag()
    {
        //得到摄像机到物体的向量
        Vector3 v = transform.position - Camera.main.transform.position;
        //得到摄像机与物体所在平面的距离
        float dis = Vector3.Dot(v, Camera.main.transform.forward);

        transform.position = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, dis));
    }
}

 

发布了129 篇原创文章 · 获赞 280 · 访问量 25万+

猜你喜欢

转载自blog.csdn.net/LLLLL__/article/details/104008490