You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Physics 2D Raycaster实现穿透物体点击下层目标?

解决Unity 2D穿透点击问题

默认的Physics 2D Raycaster配合IPointerClickHandler只会触发射线路径上第一个命中对象的点击事件,要实现穿透点击,直接自定义射线检测逻辑就行,步骤如下:

方法:自定义穿透点击检测脚本

在你的主相机上挂载以下脚本,手动获取所有被射线命中的对象并触发点击事件:

using UnityEngine;
using UnityEngine.EventSystems;

public class PenetrationClickHandler : MonoBehaviour
{
    private Camera _mainCamera;

    void Awake()
    {
        _mainCamera = GetComponent<Camera>();
    }

    void Update()
    {
        // 检测鼠标左键点击
        if (Input.GetMouseButtonDown(0))
        {
            // 把屏幕鼠标坐标转成世界坐标
            Vector2 mouseWorldPos = _mainCamera.ScreenToWorldPoint(Input.mousePosition);
            // 发射射线获取指定图层的所有命中2D碰撞体
            LayerMask targetLayers = LayerMask.GetMask("Table", "UI");
            RaycastHit2D[] allHits = Physics2D.RaycastAll(mouseWorldPos, Vector2.zero, float.MaxValue, targetLayers);

            // 遍历所有命中对象,触发点击事件
            foreach (RaycastHit2D hit in allHits)
            {
                IPointerClickHandler clickComponent = hit.collider.GetComponent<IPointerClickHandler>();
                if (clickComponent != null)
                {
                    PointerEventData eventData = new PointerEventData(EventSystem.current);
                    eventData.position = Input.mousePosition;
                    clickComponent.OnPointerClick(eventData);
                }
            }
        }
    }
}

关键说明

  1. 用Physics2D.RaycastAll替代EventSystem的默认射线检测,能一次性获取所有命中对象
  2. 通过LayerMask精准指定要检测的图层(比如你的「Table」和「UI」图层),避免无关物体干扰
  3. 遍历命中对象时,手动调用每个对象上IPointerClickHandler接口的OnPointerClick方法,实现穿透触发

如果不需要区分图层,直接去掉LayerMask参数即可,Physics2D.RaycastAll会检测所有开启碰撞体的对象。

内容的提问来源于stack exchange,提问作者Tomessertor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 01:22:43