Last active
August 1, 2022 07:11
-
-
Save fguillen/dc53b2fbc74c744a4f4cdd6976a2ff36 to your computer and use it in GitHub Desktop.
Unity, generate a random point into a Polygon
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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