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;
        //鼠标松开后回到原点
    } 
}

效果 如下图所示
Unity—UGUI游戏摇杆的制作_第1张图片

你可能感兴趣的:(Unity-UGUI)