天天看点

Unity中游戏摇杆的制作,不借助任何插件手动实现【最简单易懂实用的方式】

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

/// <summary>
/// 摇杆脚本【挂到可以设定的拖拽区域UI上】
/// </summary>
public class M_Touch : MonoBehaviour,IPointerDownHandler,IPointerUpHandler,IDragHandler {

    public Transform TouchBack;//摇杆背景圈
    public Transform Touch;//摇杆图标
    //摇杆最大位移【应根据屏幕变化比例变化】
    private const float MaxLen = 100;
    public Vector2 starVec = Vector2.zero;

    void Start()
    {
        starVec = Touch.position;//记录摇杆本来屏幕的位置
    }

    public void OnPointerDown(PointerEventData eventData)
    {
        DoMove(eventData);
    }

    public void OnPointerUp(PointerEventData eventData)
    {
        Touch.localPosition = Vector2.zero;//抬起手指回最初点
    }

    public void OnDrag(PointerEventData eventData)
    {
        DoMove(eventData);
    }
    private void DoMove(PointerEventData eventData)
    {
        Vector2 dir = eventData.position - starVec;
        float len = dir.magnitude;
        if (len > MaxLen)
        {
            //限定向量长度
            Vector2 clampDir = Vector2.ClampMagnitude(dir, MaxLen);
            Touch.position = starVec + clampDir;
        }
        else
        {
            Touch.position = eventData.position;
        }
    }
}