试图创建一个随机的“太阳系”

时间:2016-10-30 22:31:08

标签: java swing graphics

这是Planet类:

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

在评论中询问您是否需要更多代码,我知道这是一个noob问题,但我无法弄清楚为什么轨道不与行星对齐。感谢。

1 个答案:

答案 0 :(得分:2)

问题在于以下两行:

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))));

因为您分别拨打r.nextInt(360)两次,所以每次都会得到一个不同的随机数。

结果是x和y坐标是针对不同角度的,我认为很清楚为什么这会是一个问题。

解决方案非常简单:只需调用r.nextInt一次并保存结果:

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

我认为这应该可以解决问题。