绘制对撞机边界 (Unity)

Drawing collider boundaries (Unity)

各位!

我运行陷入了这个问题。我需要画出敌人攻击的半径。半径需要与悬挂在其上的 SphereCollider 的半径相等。我试图在绘制圆圈的 LineRenderer 的帮助下完成它。是的,实际上它正确地绘制了圆,但是我的圆的半径小于它上面的碰撞器的半径,尽管我已经从 GetComponent() 中给出了变量的值。

有人知道问题出在哪里吗?

我的部分代码:

    float x;
    float z;

    float change = 2 * (float)Math.PI / segments;
    float angle = change;

    x = Mathf.Sin(angle) * radius;
    _line.SetPosition(0, new Vector3(x, 0, Mathf.Cos(angle) * radius));

    for (int i = 1; i < (segments + + 2); i++)
    {
        x = Mathf.Sin(angle) * radius;
        z = Mathf.Cos(angle) * radius;

        yield return new WaitForSeconds(drawSpeed);
        _line.SetPosition((int)i, new Vector3(x, 0, z));

        angle += change;
    }

这有点老套,但我已经为这类事情使用了球体轮廓 sprite。只需将它放在游戏对象上并确保它的缩放比例与您的对撞机相同。无需花哨的线条画。

敌人的攻击范围不要使用对撞组件!

与其添加 圆形碰撞器组件,不如通过代码和物理学添加碰撞器

你应该怎么做?

这是一个通过代码和物理学使用对撞机的示例

float theCircleRadios = /* You radios */;
Collider2D[] detectedEnemiesColliders = Physics2D.OverlapCircleAll(theCirclePosition, theCircleRadios, DetectedLayers);

然后让你的行 lineRenderer radios == theCircleRadios.

在您提到的评论中,您的半径来自

float radius = _collider.radius;

其中 _collider 是您的 SphereCollider

所以请注意 SphereCollider.radius

The radius of the sphere measured in the object's local space.

The sphere radius will be scaled by the transform's scale.

在我看来,您的对象或其父对象之一的缩放比例与 1,1,1 不同,在这种情况下,实际最终半径将受到该比例的影响。

您需要根据 transform.lossyScale 相应地缩放半径,例如

// Get the lossyScale
// this is the localScale of all parent objects and this localScale combined
var lossyScale = _collider.transform.lossyScale;

// find the biggest extends of the lossyScale
// if you already know they are always equal anyway simply use e.g. lossyScale.x instead   
float maxScale = 0;
for(var i = 0; i < 3; i++)
{
   maxScale = Mathf.Max(maxScale, Mathf.Abs(lossyScale[i]);
}

float radius = _collider.radius * maxScale;