看了不少的动态摇杆的做法,感觉多少有点复杂。于是自己手动写了一个
效果如图
项目演示案列:
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);
}
}