c# - 我怎样才能使我的 Raycast2D 引用它击中的每个对象?
问题描述
我想编写代码,从我的播放器投射光线,并且对于光线触及的每个敌人,我希望能够引用该敌人,以执行诸如查找最远的敌人或调用敌人内部的方法等操作。目前在我的 Player 对象中,我有以下代码:
Vector2 mousePos = new Vector2(Camera.main.ScreenToWorldPoint(Input.mousePosition).x, Camera.main.ScreenToWorldPoint(Input.mousePosition).y);
Vector2 castPointPos = new Vector2(castPoint.position.x, castPoint.position.y);
RaycastHit2D hit = Physics2D.Raycast(castPointPos, mousePos-castPointPos, 5, whatToHit);
Debug.DrawLine(castPointPos, mousePos, Color.green);
if (hit.collider != null)
{
Debug.DrawLine(castPointPos, hit.point, Color.red);
Debug.Log("I'm hitting " + hit.collider.name);
}
这工作得很好,但我只能用它来引用光线接触的第一个对象。之后如何创建一个存储每个对象的数组?
解决方案
您可以使用Physics2D.RaycastAll
,或者RaycastNonAlloc
如果您担心性能。
Vector2 origin; //init this variable
Vector2 direction; //init this variable
RaycastHit2D[] = Physics2D.RaycastAll(origin, direction);
(请注意,您返回的数组不是按距离排序的,因此您必须自己管理。)
推荐阅读
- python - 列表中的函数 .assigned()
- visual-studio-code - VS 2017 和 2019 中缺少实体框架
- python - 使用 Python flask-restplus/x 在 Swagger 中订购参数
- laravel - consoletvs v6 图表 X 轴:是否可以有不规则刻度的日期(或时间戳)?
- java - 语法错误,在Eclipse中导入TestNG的@Test注解时插入“EnumBody”来完成ClassBodyDeclarations错误
- max - 读取 MAX30101 HR 和 SP02 数据
- c - 由于未定义引用,无法在 Windows 下编译共享库
- identification - 是否存在一种语言,其中 `print, "hello, world!"` 是有效的 Hello World 程序?
- kubernetes - 您将如何确保您的 GKE 集群靠近您的最终客户端?
- python - 通过键(整数)返回排序值列表的高效字典排序