Skip to content

Instantly share code, notes, and snippets.

@fguillen
Last active August 1, 2022 07:11
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save fguillen/dc53b2fbc74c744a4f4cdd6976a2ff36 to your computer and use it in GitHub Desktop.
Save fguillen/dc53b2fbc74c744a4f4cdd6976a2ff36 to your computer and use it in GitHub Desktop.
Unity, generate a random point into a Polygon
using System;
using UnityEngine;
public class RandomPointInCollider
{
Collider2D collider;
Vector3 minBound;
Vector3 maxBound;
int maxAttempts;
public RandomPointInCollider(Collider2D collider, int maxAttempts = 100)
{
this.maxAttempts = maxAttempts;
this.collider = collider;
this.minBound = collider.bounds.min;
this.maxBound = collider.bounds.max;
}
public Vector3 RandomPoint()
{
Vector3 randomPoint;
int attemptsDone = 0;
do {
randomPoint =
new Vector3(
UnityEngine.Random.Range(minBound.x, maxBound.x),
UnityEngine.Random.Range(minBound.y, maxBound.y),
UnityEngine.Random.Range(minBound.z, maxBound.z)
);
attemptsDone ++;
if(attemptsDone > maxAttempts)
throw new InvalidOperationException("Max attempts reached: " + attemptsDone);
} while(!collider.OverlapPoint(randomPoint));
return randomPoint;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment