Unity 浮动摇杆的写法,附源码与案例

看了不少的动态摇杆的做法,感觉多少有点复杂。于是自己手动写了一个
效果如图
请添加图片描述

项目演示案列:
https://github.com/aiterlya/UnityDynamicJoy

简单说下原理:
1,使用了Unity的EventSystems,
按下的时候,记录一个BGpos坐标,把摇杆的背景图片挪到坐标上去
拖拽的时候,记录下拖拽的坐标HandlePos,handlePos与BGpos一减,就获得了向量
2,显隐
用来CanvasGroud与Dotween;
简单说下使用需求:
在这里插入图片描述
源码如图:

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

[RequireComponent(typeof(CanvasGroup))]
public class DynamicJoy : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IDragHandler
{

    private RectTransform BG;//摇杆的背景图片
    private RectTransform Handle;//摇杆的中心杆

    private Vector2 BGPos;//背景图片位置
    private Vector2 HandldPos;//摇杆位置

    private Vector2 Dirction; //摇杆的方向
    private float radius;//背景图的半径
    public void OnDrag(PointerEventData eventData)
    {


        HandldPos = eventData.position;
        Vector2 Dirct = HandldPos - BGPos;

        if (Dirct.magnitude > radius)   
        {
            Handle.localPosition = Dirct.normalized * radius;
        }
        else
        {
            Handle.position = eventData.position;
        }

        Dirction = Dirct / radius; //向量值控制在1以内

    }

    public void OnPointerDown(PointerEventData eventData)
    {
        BgHide(false);
        BGPos = eventData.position;
        BG.position = BGPos;
    }

    public void OnPointerUp(PointerEventData eventData)
    {
        BgHide(true);
        Dirction = Vector2.zero;
        Handle.position = BGPos;

    }
    /// <summary>
    /// 返回方向位置
    /// </summary>
    /// <returns></returns>
    public Vector2 GetAxis()
    {

        return Dirction.magnitude < 1 ? Dirction : Dirction.normalized;
    }

    void Start()
    {
        BG = transform.Find("BG").GetComponent<RectTransform>();
        Handle = transform.Find("BG/Handle").GetComponent<RectTransform>();
        radius = BG.sizeDelta.x * 0.5f;
    }

    public void BgHide(bool _hide)
    {
        int hide = _hide ? 0 : 1;
        BG.GetComponent<CanvasGroup>().DOFade(hide, 0.3f);

    }
   
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值