Question by
luboslehocky · Feb 27, 2021 at 12:35 AM ·
2d gamecollider2dprefab-instancerandomspawningrandom spawn
Spawn prefab randomly over polygon collider 2d
I have attached pollygon collider 2d on this gameObject.
This gameObject is parent of another gameObject (just small circle).
I want that small circle to randomly spawn somwhere on pollygon collider.
I tried something like this:
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();
}
This script is attached to that small circle. In 80% cases is good result but sometimes it get weird something like this:
Can someone help me please, becouse i tried almost everything
screenshot-2.jpg
(37.8 kB)
polygon.jpg
(35.1 kB)
Comment