如何让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
相关产品推荐
相关产品推荐

