How to get random points from a Box Collider2D

本小妞迷上赌 提交于 2019-12-11 08:53:17

问题


I am trying to spawn particle effects at random points of a Box Collider2D. I know how to do this for a PolygonCollider2D but was just wondering if there is a similar way to do it for a Box Collider2D. I am trying to convert this code for a Box Collider. Can someone maybe point me in the right direction?

PolygonCollider2D col = GetComponent<PolygonCollider2D>();
int index = Random.Range(0, col.pathCount);
Vector2[] points = col.GetPath(index)
Vector2 spawnPoint = Random.Range(0, points.Length);

回答1:


No, you don't have any coordinate data for surface of Box Collider. But you can calculate it.

Lets say your box is 2a width and 2b height.

Of course you can assign two random value to decide first, x = abs(a) || y = abs(b) and thus corresponding y = rand(-b,b) || x = rand(-a, a). But it is not elegant (at least I think).

So lets do it in polar coordinate as following, where you can generate only one random value from 0 to 360 as theta.

Vector2 calCoor(double theta, int a, int b)
{
    double rad = theta * Math.PI / 180.0;
    double x, y;
    double tan = Math.Tan(rad);
    if (Math.Abs(tan) > b/ (double)a)
    {
        x = tan > 0 ? a : -a;
        y = b / Math.Tan(rad);
    } else
    {
        x = a * Math.Tan(rad);
        y = tan < 0 ? b : -b;
    }
    return new Vector2(x,y);
}

Don't forget to add this vector2 back to your Box Collider's coordinate.

You can find the eqn to transform a rectangle from Cartesian coordinate to Polar coordinate here.



来源:https://stackoverflow.com/questions/51979673/how-to-get-random-points-from-a-box-collider2d

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!