Collider2D获取随机点

Collider2D获取随机点

本文介绍了如何从Box Collider2D获取随机点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Box Collider2D的随机点处生成粒子效果.我知道如何为PolygonCollider2D做到这一点,但我只是想知道是否有类似的方法可以对Box Collider2D做到这一点.我正在尝试将此代码转换为Box Collider.有人可以指出我正确的方向吗?

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);

推荐答案

不,您没有Box Collider曲面的任何坐标数据.但是你可以计算出来.

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

假设您的盒子的宽度为2a,高度为2b.

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

当然,您可以分配两个随机值来首先确定x = abs(a) || y = abs(b),从而确定相应的y = rand(-b,b) || x = rand(-a, a).但这并不优雅(至少在我看来).

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).

因此,请按如下所示在极坐标中进行操作,在该极坐标中,您只能生成一个从0到360的随机值作为theta.

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);
}

别忘了将此vector2添加回Box Collider的坐标.

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.

这篇关于如何从Box Collider2D获取随机点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 02:25