1、搖桿界面制作
簡單搖桿圖片下載
鏈接:https://pan.baidu.com/s/1H3V7Nw2tfGwO33S6ijwtvw
提取碼:7dtf
2、代碼
搖桿監聽事件,單獨寫一個類(可復用)
using System;
using UnityEngine;
using UnityEngine.EventSystems;
//后面三個為Unity的按下、按起、拖拽的事件接口
/// <summary>
/// 監聽事件腳本單獨寫出,使用時可以直接添加,提高復用性
/// </summary>
public class RockerListener : MonoBehaviour,IPointerDownHandler,IPointerUpHandler,IDragHandler
{
//定義3個action委托
public Action<PointerEventData> onPointerDown;
public Action<PointerEventData> onPointerUp;
public Action<PointerEventData> onDrag;
//這三個事件分別在鼠標按下、鼠標抬起、鼠標拖拽時觸發
public void OnPointerDown(PointerEventData eventData)
{
if (onPointerDown != null)
{
onPointerDown(eventData);
}
}
public void OnPointerUp(PointerEventData eventData)
{
if (onPointerUp != null)
{
onPointerUp(eventData);
}
}
public void OnDrag(PointerEventData eventData)
{
if (onDrag != null)
{
onDrag(eventData);
}
}
}
掛載在搖桿上的具體類
using System;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class RockerTest : MonoBehaviour
{
//有效點擊區域、外搖桿、內搖桿
private GameObject rockerRange;
private GameObject clickOutImg;
private GameObject clickInImg;
//搖桿默認位置、點擊位置、內外搖桿最大距離差
private Vector2 defaultPos;
private Vector2 clickPos;
private float maxDistance = 50;
private void Start(){
InitGO();
InitListener();
}
private void Update(){
}
/// <summary>
/// 初始化游戲物體對象
/// </summary>
private void InitGO()
{
rockerRange = this.gameObject;
clickOutImg = transform.Find("clickOutImg").gameObject;
clickInImg = transform.Find("clickOutImg/clickInImg").gameObject;
defaultPos = clickOutImg.transform.position;
}
/// <summary>
/// 初始化搖桿監聽事件
/// </summary>
private void InitListener()
{
RockerListener listener = GetOrAddComponent<RockerListener>(rockerRange);
//鼠標按下時移動到按下的位置
listener.onPointerDown = (PointerEventData data) =>
{
clickOutImg.transform.position = data.position;
clickPos = data.position;
};
//抬起時回到原位
listener.onPointerUp = (PointerEventData data) =>
{
clickOutImg.transform.position = defaultPos;
clickInImg.transform.localPosition = Vector2.zero;
};
//拖拽時小搖桿在大搖桿的一定范圍內移動
listener.onDrag = (PointerEventData data) =>
{
Vector2 dir = data.position - clickPos;
float len = dir.magnitude;
if (len >= maxDistance)
{
//限制內搖桿的最大移動距離
Vector2 limitDistance = Vector2.ClampMagnitude(dir, maxDistance);
clickInImg.transform.position = clickPos + limitDistance;
}
else
{
clickInImg.transform.position = data.position;
}
};
}
/// <summary>
/// 得到或添加T組件到物體上(限制T范圍為component)
/// </summary>
private T GetOrAddComponent<T>(GameObject go) where T : Component
{
T t = go.GetComponent<T>();
if (t == null)
{
t = go.AddComponent<T>();
}
return t;
}
}