gpt4 book ai didi

java - 尝试创建随机的 "solar system"

转载 作者:行者123 更新时间:2023-12-02 03:15:47 24 4
gpt4 key购买 nike

这是 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

如果您需要更多代码,请在评论中询问,我知道这是一个菜鸟问题,但我就是不明白为什么轨道与行星不对齐。谢谢。

最佳答案

问题出在以下两行:

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

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

关于java - 尝试创建随机的 "solar system",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40334350/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com