Skip to content

Instantly share code, notes, and snippets.

@SiarheiPilat
Created October 20, 2020 15:44
Show Gist options
  • Save SiarheiPilat/0a8b184aebc1966cd09bc29e2f9d7036 to your computer and use it in GitHub Desktop.
Save SiarheiPilat/0a8b184aebc1966cd09bc29e2f9d7036 to your computer and use it in GitHub Desktop.
Spawn objects (or randomise their position) inside an area defined by a 2D collider.
using UnityEngine;
public class RandomiseInsideCollider : MonoBehaviour
{
public Collider2D AreaPolygonCollider;
Bounds Bounds;
Vector3 BoundX1, BoundX2, BoundY1, BoundY2;
Vector3 randomPos;
public Transform go;
void Start()
{
Bounds = AreaPolygonCollider.bounds;
BoundX1 = Bounds.min;
BoundY2 = Bounds.max;
BoundX2 = new Vector3(Bounds.max.x, Bounds.min.y);
BoundY1 = new Vector3(Bounds.min.x, Bounds.max.y);
RandomizePosition();
}
void RandomizePosition()
{
randomPos = new Vector3(Random.Range(BoundX1.x, BoundX2.x), Random.Range(BoundX2.y, BoundY2.y), 0.0f);
if (Physics2D.OverlapPoint(randomPos))
go.position = randomPos; // alternatively, instantiate object here
else RandomizePosition();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment