首页 > 解决方案 > 我怎样才能使我的 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);
}

这工作得很好,但我只能用它来引用光线接触的第一个对象。之后如何创建一个存储每个对象的数组?

标签: c#unity3d

解决方案


您可以使用Physics2D.RaycastAll,或者RaycastNonAlloc如果您担心性能。

Vector2 origin; //init this variable
Vector2 direction; //init this variable

RaycastHit2D[] = Physics2D.RaycastAll(origin, direction);

链接到文档

(请注意,您返回的数组不是按距离排序的,因此您必须自己管理。)


推荐阅读