以下方法适合在Editor下使用,在移动端无效(转自雨松)
void Update ()
{
if (Input.touchCount > 0 && Input.GetTouch (0).phase == TouchPhase.Began) {
if (IsPointerOverGameObject (Input.GetTouch (0).fingerId)) {
Debug.Log("当前触摸在UI上");
} else {
Debug.Log("当前没有触摸在UI上");
}
}
}
bool IsPointerOverGameObject( int fingerId )
{
EventSystem eventSystem = EventSystem.current;
return ( eventSystem.IsPointerOverGameObject( fingerId )
&& eventSystem.currentSelectedGameObject != null );
}
当然也可以使用射线的原理来判断(无论移动端还是window下都可使用)需要传入的参数为画布和屏幕点击位置
/// <summary>
/// Cast a ray to test if screenPosition is over any UI object in canvas. This is a replacement
/// for IsPointerOverGameObject() which does not work on Android in 4.6.0f3
/// </summary>
private bool IsPointerOverUIObject(Canvas canvas, Vector2 screenPosition) {
// Referencing this code for GraphicRaycaster https://gist.github.com/stramit/ead7ca1f432f3c0f181f
// the ray cast appears to require only eventData.position.
PointerEventData eventDataCurrentPosition = new PointerEventData(EventSystem.current);
eventDataCurrentPosition.position = screenPosition;
GraphicRaycaster uiRaycaster = canvas.gameObject.GetComponent<GraphicRaycaster>();
List<RaycastResult> results = new List<RaycastResult>();
uiRaycaster.Raycast(eventDataCurrentPosition, results);
return results.Count > 0;
}

本文提供了一种在移动端Unity3D环境下处理触摸事件的方法,解决了传统方法在移动端失效的问题。通过使用特定的输入参数,实现触摸在UI上的准确判断。同时,介绍了射线原理的应用,使得该方法在不同平台下都能有效运行。
8090

被折叠的 条评论
为什么被折叠?



