Sorry for the strange topic name, couldn´t think of a good way to describe it. I´m basically trying to achieve the following:
I'm placing items randomly on the screen, but these items shouldn't be placed near eachother at a given distance. This is the process I have in my head right now:
- generate a random location
- check if this location is not near any other objects
- it is near -> start the process over to generate a new item (till it is not near anymore)
I've run into this scenario multiple times but could never think of a way to efficiently do this, while I do feel that there is a simple way to do it. Here is the implementation I have right now. I feel like I should use a while loop but I can't get my around how to do it. The code is in AS3 but that shouldn't matter.
public function generatePlanetsFromXML(xml:XML):void
{
planets = new Array();
for (var i:int = 0; i < xml.projects.project.length(); i++) {
var planet:Planet = new Planet();
planet.data = xml.projects.project[i];
planet.radius = (Math.random() * 20) + 20;
addChild(planet);
addObject(planet);
planets.push(planet);
calculatePlanetLocation(planet, i);
}
}
private function calculatePlanetLocation(planet:Planet, i:int):void
{
var randomX:int = (Math.random() * (worldwidth - planet.width)) + 20;
var randomY:int = (Math.random() * (worldheight - planet.height)) + 20;
//get a location that isn't close to another planet
//keep looping till the distance is higher than minimum distance
for (var j:int = 0; j < planets.length; j++) {
if (i != j) {
var dx:int = planets[j].x - randomX;
var dy:int = planets[j].y - randomY;
var distance:int = Math.sqrt((dx * dx) + (dy * dy));
if (distance < minPlanetDistance) {
trace("retry getting location..");
planet.alpha = 0.3;
calculatePlanetLocation(planet, i);
}else {
//distance is fine, planet can be placed!
planet.x = randomX;
planet.y = randomY;
}
}else if (i == 0) {
//first planet should always be placed
planet.x = randomX;
planet.y = randomY;
}
}
}