无法让 RaycastHit2D 正常工作

Not able to get RaycastHit2D work properly

在我的游戏中,我正在画一条线并限制线的长度,如果它碰到任何碰撞器,我正在使用 raycasthit2d。但它并不总是有效。 我使用 Debug.DrawRay 来查看它是如何工作的,但它并没有像我预期的那样工作。 下面是我的代码

float distance = Vector3.Distance(startPoint, endPoint);
RaycastHit2D hit = Physics2D.Raycast(startPoint, endPoint,distance, layerMask :1 << 8);
Debug.DrawRay(startPoint,endPoint,Color.red,40f);
Debug.Log("startPoint" + startPoint + " endPoint:" + endPoint+" distance:"+distance);
if (hit.collider != null/* && hit.collider.CompareTag(GameConstants.TAG_OF_RESTRICT_LINES_OVER_PLAYER)*/)
{
    Debug.Log(hit.collider.gameObject.name);
    endPoint = hit.point;
    Debug.Log(" :hit:" + hit.point);
}
Vector3[] array = new Vector3[] { startPoint, endPoint };
lr.SetPositions(array);

控制台输出

startPoint(-4.9, -2.7, 1.0) endPoint:(1.1, -3.7, 1.0) distance:6

我已附上相同的屏幕截图。

我正在使用 startPointendPoint 来画线,并将光线投射作为各自的起点和方向。

如果有人能指出我的错误或实现此目的的替代方法,那将是一个很大的帮助。

我的目标是绘制与 lineRenderer 绘制的线完全一样的光线投射线。

我认为问题是你给 Physics2d.Raycast 错误的参数。

这是文档的 link: https://docs.unity3d.com/ScriptReference/Physics2D.Raycast.html

在您的代码中,第二个参数无效:

Physics2D.Raycast(startPoint, endPoint,distance, layerMask :1 << 8);

第二个参数是一个向量,你给它一个点。你应该给出一个基于 startPoint 和 endPoint 的归一化向量。