2016-10-30 19 views
0

这里是地球类:试图创建一个随机“太阳系”

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问题,但我就是不明白,为什么轨道不与行星排队。谢谢。

+2

欢迎计算器!乍一看,你的代码看起来很好。你可以发布Planet类的其余部分吗?如果你想让它更容易为人们帮助,你可以尝试做一个[Minmal,完全和可验证的示例](http://stackoverflow.com/help/mcve)。 – 11684

+0

没关系,我想通了,问题是什么。 – 11684

+0

我在全班编辑。 – Tom

回答

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

我想这应该解决的问题。

+0

谢谢!这很明显,但我无法弄清楚。 – Tom