You need to enable JavaScript to run this app. 如何让Raycast2D获取并存储射线命中的所有物体?
优惠活动
大模型
产品
解决方案
定价
更多

如何让Raycast2D获取并存储射线命中的所有物体?

解决方案

你当前使用的Physics2D.Raycast仅返回射线命中的第一个物体,要获取射线路径上所有命中物体,直接替换为批量检测API Physics2D.RaycastAll即可。该方法会返回RaycastHit2D[]类型的数组,存储所有符合检测条件的命中结果,默认按碰撞点到发射点的距离由近到远排序。

修改后的完整示例代码
Vector2 mouseWorldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 castPointPos = castPoint.position;
// 发射射线获取所有命中物体
RaycastHit2D[] allHits = Physics2D.RaycastAll(castPointPos, mouseWorldPos - castPointPos, 5f, whatToHit);

Debug.DrawLine(castPointPos, mouseWorldPos, Color.green);
if (allHits.Length > 0)
{
    // 遍历所有命中物体
    foreach (RaycastHit2D hit in allHits)
    {
        Debug.DrawLine(castPointPos, hit.point, Color.red);
        Debug.Log("命中物体:" + hit.collider.name);
        // 获取敌人脚本引用,调用内部方法
        Enemy enemy = hit.collider.GetComponent<Enemy>();
        if (enemy != null)
        {
            enemy.YourCustomMethod(); // 替换为你自己实现的敌人方法
        }
    }

    // 直接获取最远的命中敌人(数组最后一位为距离最远的命中结果)
    RaycastHit2D farthestHit = allHits[allHits.Length - 1];
    Enemy farthestEnemy = farthestHit.collider.GetComponent<Enemy>();
    if (farthestEnemy != null)
    {
        Debug.Log("最远敌人为:" + farthestEnemy.gameObject.name);
    }
}
注意事项
  • 代码中的Enemy需要替换为你项目中实际的敌人脚本类名
  • 如果你不需要检测触发器碰撞体,可以在调用RaycastAll时追加第五个参数QueryTriggerInteraction.Ignore过滤触发器
  • 如需按由远到近的顺序处理命中物体,直接倒序遍历allHits数组即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 01:24:04