天天看點

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

繼續閱讀