Unity—UGUI遊戲搖桿的製作

using UnityEngine;
using System.Collections;
using System;//新增命名空間 
using UnityEngine.EventSystems;//新增

public class DragJoyStick : 

**//這倆個是新增接口 IDragHandler,IEndDragHandler**

MonoBehaviour,IDragHandler,IEndDragHandler {

    private Vector3 direction;
    public float maxDistance;//可以拖動的最大距離

    public void OnDrag(PointerEventData eventData)
    {
        transform.position = Input.mousePosition;
        //鼠標拖動搖桿移動 
        if (Vector3.Distance(Vector3.zero,transform.localPosition)>maxDistance)
        {
            direction = transform.localPosition - Vector3.zero;//獲取方向
            transform.localPosition = direction.normalized * maxDistance;//當超出範圍一直在邊界
        }
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        transform.localPosition = Vector3.zero;
        //鼠標鬆開後回到原點
    } 
}

效果 如下圖所示
遊戲搖桿效果圖

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章