Tom Tom - 1 month ago 5
Java Question

Trying to create a randomized "solar system"

Here is the Planet class:

public class Planet extends CelestialBody {

private static Random r = new Random();
private static Star star;

public Planet(Star star, int orbitRadius, int x, int y){
name = "PLACEHOLDER";
radius = Tools.intBetween(Settings.MAX_PLANET_SIZE, Settings.MIN_PLANET_SIZE);
color = Tools.rObjFromArray(Settings.PLANET_COLORS);
this.star = star;
this.orbitRadius = orbitRadius;
this.x = x; this.y = y;
}


public static Planet createNewPlanet(Star star, int orbitRadius){
int px = (int) (star.x + orbitRadius * Math.cos(Math.toRadians(r.nextInt(360))));
int py = (int) (star.y + orbitRadius * Math.sin(Math.toRadians(r.nextInt(360))));

return new Planet(star, orbitRadius, px, py);
}

public void render(Graphics g){
//Draw orbit
g.setColor(Color.white);
g.drawOval(star.x - orbitRadius, star.y - orbitRadius, orbitRadius * 2, orbitRadius * 2);

//Draw planet
g.setColor(color);
g.fillOval(x - radius, y - radius, radius * 2, radius * 2);
}
}


orbitRadius = distance from planet to star (random);

radius = planet's radius (random)

result

Ask in the comments if you need any more code, and I know this is a noob question, but I just can't figure out why the orbits dont line up with the planets. Thanks.

Answer

The problem is in the following two lines:

int px = (int) (star.x + orbitRadius * Math.cos(Math.toRadians(r.nextInt(360))));
int py = (int) (star.y + orbitRadius * Math.sin(Math.toRadians(r.nextInt(360))));

Because you call r.nextInt(360) two separate times, you get a different random number each time.

The consequence is that the x and y coordinates are for different angles, I think it's clear why this would be a problem.

The solution is very simple: call r.nextInt once and save the result:

int randomAngle = Math.toRadians(r.nextInt(360));
int px = (int) (star.x + orbitRadius * Math.cos(randomAngle));
int py = (int) (star.y + orbitRadius * Math.sin(randomAngle));

I think this should solve the problem.

Comments