UGUI判断鼠标或者手指是否点击在UI上

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

以下方法适合在Editor下使用,在移动端无效(转自雨松)

void Update(){
if (Input.GetMouseButtonDown(0) )
{
Debug.Log(EventSystem.current.gameObject.name);
if (EventSystem.current.IsPointerOverGameObject())
Debug.Log("当前触摸在UI上");
else Debug.Log("当前没有触摸在UI上");
}
}
在移动端无效的原因是:IsPointerOverGameObject()在editor下默认传入pointID为-1,在移动端需要传入具体fingerid值
因此在移动端可以考虑以下方法:

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;
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值