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;
}
}
UGUI游戏摇杆
最新推荐文章于 2024-06-13 20:12:46 发布