天天看點

Unity中實作拖拽操作

一: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 Awake()
    {
        Input.multiTouchEnabled = false;
    }

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

繼續閱讀