95 lines
3.1 KiB
C#
95 lines
3.1 KiB
C#
using UnityEngine;
|
|
using UnityEngine.UI;
|
|
using UnityEngine.EventSystems;
|
|
using System.Collections.Generic;
|
|
using FairyGUI;
|
|
using Roy;
|
|
|
|
public class UIScreenTapTrigger : SingletonMonoBehaviour<UIScreenTapTrigger>
|
|
{
|
|
public Canvas canvas; // 目标 Canvas
|
|
private GraphicRaycaster raycaster;
|
|
private EventSystem eventSystem;
|
|
|
|
private RectTransform _canvasRect;
|
|
private float _scaleX, _scaleY;
|
|
|
|
private float _ignoreY;
|
|
|
|
private void Start()
|
|
{
|
|
// 获取 Canvas 上的 GraphicRaycaster 和 EventSystem
|
|
raycaster = canvas.GetComponent<GraphicRaycaster>();
|
|
eventSystem = EventSystem.current;
|
|
|
|
_canvasRect = canvas.GetComponent<RectTransform>();
|
|
|
|
// 分别计算 X 和 Y 方向的缩放因子
|
|
_scaleX = Screen.width / _canvasRect.sizeDelta.x;
|
|
_scaleY = Screen.height / _canvasRect.sizeDelta.y;
|
|
|
|
}
|
|
|
|
public void SetIgnoreY(float ignoreY)
|
|
{
|
|
_ignoreY = ignoreY;
|
|
}
|
|
|
|
// 将 iOS 的比例坐标转换为 Unity 坐标
|
|
private Vector2 ConvertToUnityPosition(Vector2 ratioPosition)
|
|
{
|
|
|
|
// Debug.LogError($"转换canvasRect size{_canvasRect.sizeDelta.x}, {_canvasRect.sizeDelta.y} ");
|
|
// Debug.LogError($"转换screen{Screen.width}x{Screen.height} 当前scale{_scaleX}x{_scaleY}" );
|
|
// 计算屏幕坐标并翻转 Y 轴
|
|
float x = ratioPosition.x * _canvasRect.sizeDelta.x * _scaleX;
|
|
float y = (1 - ratioPosition.y) * _canvasRect.sizeDelta.y * _scaleY;
|
|
|
|
return new Vector2(x, y);
|
|
}
|
|
|
|
|
|
// 检测特定屏幕坐标的 UI 按钮并触发
|
|
public bool TriggerButtonAtScreenPosition(Vector2 screenPosition)
|
|
{
|
|
// Debug.LogError($"转换前比例{screenPosition}");
|
|
screenPosition = ConvertToUnityPosition(screenPosition);
|
|
|
|
if (screenPosition.y < _ignoreY)
|
|
{
|
|
Debug.LogError($"TouchClickPoint 忽略当前高度{screenPosition.y} 限制范围Y{_ignoreY}");
|
|
return false;
|
|
}
|
|
// Debug.LogError($"转换后坐标{screenPosition}");
|
|
// 设置射线检测的事件数据
|
|
PointerEventData pointerEventData = new PointerEventData(eventSystem)
|
|
{
|
|
position = screenPosition
|
|
};
|
|
|
|
// 用于存储检测结果
|
|
List<RaycastResult> results = new List<RaycastResult>();
|
|
|
|
// 对屏幕坐标进行射线检测
|
|
raycaster.Raycast(pointerEventData, results);
|
|
|
|
// 遍历检测结果
|
|
foreach (RaycastResult result in results)
|
|
{
|
|
var target = result.gameObject.GetComponent<Button>();
|
|
if (target != null)
|
|
{
|
|
// 触发按钮点击事件
|
|
// button.onClick.Invoke();
|
|
|
|
// ExecuteEvents.Execute(result.gameObject, pointerEventData, ExecuteEvents.submitHandler);
|
|
ExecuteEvents.Execute(result.gameObject, pointerEventData, ExecuteEvents.pointerClickHandler);
|
|
|
|
Debug.Log("Button triggered: " + result.gameObject.name);
|
|
return true;
|
|
}
|
|
}
|
|
|
|
return false;
|
|
}
|
|
} |