I’m currently co-oping a space game with a friend of mine. This game will have the random spawning of planets in the galaxy. It would look rather weird in a top down world to have planets on top of eachother, so I tried to write this bit of code to make it so planets would stay atleast 32 pixels away from another planet. However, planets realize that they are inside of other planets, but never change their position. At least, from a bit of debugging thats what I’ve concluded. (I very well could be inaccurate.) The code below is the exact code in the game. Could you review it? I feel like fresh eyes could help me solve the problem as I can’t seem to figure it out. Or maybe I’m going about this wrong. Here is my diagram of how the code below is supposed to look through each planet.
- Generates a random set of coords
- Checks those coords to see if they fall inside another planet[list]
[li]If so, regenerate coords and re-loop through all the planets - Repeat infinitely until a non-offending pair of coords are found
[/li] - Generate a planet with the non-offending set of coords
[/list]
int x;
int y;
for(int i = 0; i < numberOfPlanets; i++) {
x = new Random().nextInt(640-32);
y = new Random().nextInt(480-32);
for(int ii = 0; ii < planets.size(); ii++) {
temp = planets.get(ii);
if((((x >= temp.x) && (x <= temp.x + temp.getWidth()+32) && ((y >= temp.y) && (y <= temp.y + temp.getHeight()))))) {
x = new Random().nextInt(640-32);
y = new Random().nextInt(480-32);
ii=0;
System.out.println(x + ", " + y + " || " + temp.getX() + ", " + temp.getY());
}
}
addPlanet(new TestPlanet(x, y, Game.NONE));
}