Unity 实现简单的360度 射线检测 扇形 伞形

发布于 2023-04-23  170 次阅读


private Collider2D collider2D;
private void Awake()
{
    collider2D = GetComponent<Collider2D>();
}
// 检测360度范围内是否有敌人
private void Detection()
{
    float startAngle = 0f;
    float endAngle = 360f;
    float radius = 1f; // 半径
    float distance = 10f; // 射线长度
    startAngle *= Mathf.Deg2Rad;
    endAngle *= Mathf.Deg2Rad;
    Vector2 startPoint = (Vector2)collider2D.bounds.center + collider2D.offset;
    for (float t = startAngle; t <= endAngle; t += Mathf.PI / 16f)
    {
        Vector2 direction = new Vector2(Mathf.Cos(t), Mathf.Sin(t));
        RaycastHit2D hit = Physics2D.Raycast(startPoint + direction * radius, direction, distance);
        if (hit.collider != null)
        {
            Debug.DrawLine(startPoint + direction * radius, hit.point, Color.red);
        }
        else
        {
            Debug.DrawRay(startPoint + direction * radius, direction * distance, Color.green);
        }
    }
}

在这个例子中,我们使用了 collider2D.bounds.center 和 collider2D.offset 来获得 Collider2D 的中心和偏移量,然后将其作为起点。这样,射线的起点就不会与自身重叠。