uGUI練習(五) Draggable Object


練習目標

學習制作一個可拖動的UI

一、步驟

監聽UI的Drag事件,需要我們寫一點點的代碼。

1、創建一個Panel ,設置size為(100,100)

2、創建DraggableObjectScene.cs腳本

3、把腳本綁定在Panel上

image

4、腳本內容如下:

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class DraggableObjectScene : MonoBehaviour,IDragHandler,IPointerDownHandler,IPointerUpHandler
{
    //Drag事件,設置目標的位置為鼠標的位置
    public void OnDrag(PointerEventData eventData)
    {
        GetComponent<RectTransform>().pivot.Set(0,0);
        transform.position=Input.mousePosition;
    }
    
    public void OnPointerDown(PointerEventData eventData)
    {
        //縮小
        transform.localScale=new Vector3(0.7f,0.7f,0.7f);
    }

    public void OnPointerUp(PointerEventData eventData)
    {
        //正常大小
        transform.localScale=new Vector3(1f,1f,1f);
    }
}

Class DraggableObjectScene 繼承了IDragHandler,IPointerDownHandler,IPointerUpHandler三個接口,從而可以接受到 OnDrag(PointerEventData eventData)  ,OnPointerDown(PointerEventData eventData)   ,OnPointerUp(PointerEventData eventData)  三個事件

二、事件系統

Namespace:UnityEngine.EventSystems

IDragHandler (MouseDrag)

Interface to implement if you wish to receive OnDrag callbacks.

IPointerDownHandler (MouseDown)

Interface to implement if you wish to receive OnPointerDown callbacks.

IPointerUpHandler (MouseUp)

Interface to implement if you wish to receive OnPointerUp callbacks.

三、Drag 效果

Drag UI


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM