在 Unity 中的多边形对撞机 2d 上随机生成预制件

问题描述

我在这个游戏对象上附加了 pollygon collider 2d。

enter image description here

这个游戏对象是另一个游戏对象的父对象(只是一个小圆圈)。

我希望那个小圆圈在多边形对撞机的某个地方随机生成。

我尝试过这样的事情:

private void GetBounds()
{
    polygonCollider = transform.parent.gameObject.GetComponent<PolygonCollider2D>();
    bounds = polygonCollider.bounds;
    
}

public void TargetSetPosition()
{
    x = Random.Range(bounds.min.x,bounds.max.x);
    y = Random.Range(bounds.min.y,bounds.max.y);

    transform.localPosition = new Vector2(x,y);
}
private void Start()
{
    GetBounds();
    TargetSetPosition();
}

这个脚本附在那个小圆圈上。在 80% 的情况下是好的结果,但有时它会变得很奇怪:

enter image description here

有人可以帮我吗,因为我几乎什么都试过了。

解决方法

bounds = polygonCollider.bounds 正在获取 bounding box 的边界。所以在你的第二张照片中,球在界内。

要使其位于对象的碰撞器内,您需要尝试其他方法,例如 this

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...