Spots on a circle inside boundaries
Hello. Here is my problem : I want to instanciate game objects around my player, at random spots but in a given distance. So there is an imaginary circle around my player, game objects have to appear on a spot on that circle. It also have to spawn inside my level boundaries.
So i need to obtain an array, with all the spots that are all at once on my circle and in my level boundaries, so i can pick one randomly and instanciate my object on it.
Im having some troubles with this issue, would someone have a clue ?
Answer by elenzil · May 04, 2017 at 06:41 PM
doing this in guaranteed-finite time is possible but tricky. to do that you'd want to find the intersections of the boundary with the circle, and then do a weighted-probability selection of one of the resulting arcs, and then choose a random point on that arc.
fortunately, computers are fast, so you can use a much simpler approach which is technically not guaranteed to terminate in finite time, but in practice will actually terminate quite quickly:
// returns true if a spot was found, false if not.
bool findSpot(Vector2 center, float radius, out Vector2 spot) {
// if we try this many and still can't find a spot, maybe there is no spot.
const int MAX_ATTEMPTS = 100;
for (int n = 0; n < MAX_ATTEMPTS; ++n) {
float theta = Random.Range(0, 2.0f * 3.14159265359f);
Vector2 candidate = new Vector2(Mathf.Cos(theta), Mathf.Sin(theta)) * radius;
if (spotIsWithinBoundaries(candidate)) {
// sweet.
spot = candidate;
return true;
}
}
spot = center;
return false;
}
bool spotIsWithinBoundaries(Vector2 spot) {
... this is on you ...
}
side-note, if the objects you're instantiating should not intersect with the wall, you probably want to subtract the radius of the object from the radius of the circle.
Your answer
Follow this Question
Related Questions
Randomize questions in a quiz game 2D 0 Answers
2D android swipe movement,2D Mobile Movement 0 Answers
Unity2D Player Jump Heights Inconsistent,Unity2D Inconsistent Player Jump Heights 0 Answers
Background Image Size (memory Profiler) 0 Answers
2D Lights - Sprite is appearing black in the camera view. 1 Answer