Search code examples
unity-game-engine2d2d-gamescolliderprefab

Spawn prefab randomly over polygon collider 2d in Unity


I have attached pollygon collider 2d on this gameObject.

enter image description here

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:

enter image description here

Can someone help me please, becouse i tried almost everything.


Solution

  • The bounds = polygonCollider.bounds is getting the bounds of the bounding box. So in your second pic, the ball is inside the bounds.

    To make it be inside the collider of your objects, you need to try something else, like this