UGUI游戏摇杆

21 篇文章 1 订阅
17 篇文章 0 订阅
using UnityEngine;
using UnityEngine.EventSystems;

/// <summary>
/// UGUI游戏摇杆
/// </summary>
public class Joystick : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IDragHandler
{
    public static Joystick Instance = null;
    public Transform centerTrans;
    public Vector2 moveDir = Vector2.zero;
    public bool isDraging = false;
    private float MaxMoveLen = 125;
    private System.Action<float,float> joyCB;
    void Awake(){
        Instance = this;
    }
    private void Start(){
        MaxMoveLen = (transform as RectTransform).sizeDelta.x * 0.5f;
    }
    // 添加摇杆的操作回调
    public void SetJoyCB(System.Action<float, float> pOnJoyCB){
        joyCB = pOnJoyCB;
    }
    private void OnJoy(PointerEventData eventData)
    {
        Vector3 v2Pos = eventData.position;
        Vector3 localPos = v2Pos - transform.position;
        localPos.z = 0;
        float len = localPos.magnitude;
        if (len > MaxMoveLen)
            len = MaxMoveLen;
        Vector3 pointPos = localPos.normalized * len;
        centerTrans.localPosition = pointPos;
        joyCB?.Invoke(localPos.normalized.x, localPos.normalized.y);
    }
    //开始按下摇杆
    public void OnPointerDown(PointerEventData data)
    {
        isDraging = true;
        OnJoy(data);
    }
    //摇杆拖拽中
    public void OnDrag(PointerEventData eventData)
    {
        OnJoy(eventData);
    }
    //摇杆方式弹起
    public void OnPointerUp(PointerEventData data)
    {
        isDraging = false;
        centerTrans.localPosition = Vector3.zero;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值