【发布时间】:2015-05-07 18:11:05
【问题描述】:
public void move(){
double angle;
for(int i = 0; i < planets.size(); i++){
if(Math.abs(Math.sqrt(Math.pow(ship.locX - (planets.get(i).locX + planets.get(i).radi), 2) + Math.pow(ship.locY - (planets.get(i).locY + planets.get(i).radi), 2))) < planets.get(i).gravrange){
//Distance formula between spaceship and planets to determine whether the ship is within the influence of the planet.
angle = ((Math.atan2((planets.get(i).locX + planets.get(i).radi) - ship.locX, (planets.get(i).locY + planets.get(i).radi) - ship.locY)) / Math.PI) + 1;
//The problematic math equation.
产生一个从 0 到 2 的双精度数,0 表示当 ship.locY
if(ship.locX > (planets.get(i).locX + planets.get(i).radi)){xm += Math.cos(angle) * planets.get(i).gravrate;}
else{xm -= Math.cos(angle) * planets.get(i).gravrate;}
if(ship.locY > (planets.get(i).locY + planets.get(i).radi)){ym += Math.sin(angle) * planets.get(i).gravrate;}
else{ym -= Math.sin(angle) * planets.get(i).gravrate;}
}
}
这使用数据来修改航天器的 X 和 Y 速度。
这个方程适用于大部分轨道,但在某些情况下存在一个问题,即航天器会受到逆行力,使其减速。不久之后,它开始被行星体排斥,在短时间内又开始吸引它。当航天器到达发生这种情况的原始位置时,它开始向与原始轨道相反的方向移动。
这种情况会持续发生,直到航天器开始波状运动。
有没有办法解决这个问题,还是我只是使用了错误的方程式?我已经尝试解决这个问题大约两个星期了。我目前没有受过物理和微积分方面的教育,所以我的理解有限。
编辑:cmets 对我的数学有疑问,所以我会在这里尝试回答。根据我对 atan2 的了解,它会产生一个从 -pi 到 pi 的数字。我除以 pi 得到一个从 -1 到 1 的数字,然后加 1 得到 0 到 2。然后我使用这个数字作为弧度测量值。我对弧度(单位圆)的了解是圆的弧度度量是 0 到 2pi。
编辑 2:以下代码具有非常不同的数学,但产生了预期的结果,除了在接近地球的南北“两极”时排斥而不是吸引的问题。
public void move(){
double angle;
double x1, x2, y1, y2;
for(int i = 0; i < planets.size(); i++){
x1 = ship.locX;
y1 = ship.locY;
x2 = planets.get(i).locX + planets.get(i).radi;
y2 = planets.get(i).locY + planets.get(i).radi;
if(Math.abs(Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2))) < planets.get(i).gravrange){
//Distance formula between spaceship and planets
angle = (y2 - y1)/(x2 - x1); //Gets slope of line between points.
if(angle > 0){
if(y1 > y2){
xm += Math.cos(angle) * planets.get(i).gravrate;
ym += Math.sin(angle) * planets.get(i).gravrate;
}else{
xm -= Math.cos(angle) * planets.get(i).gravrate;
ym -= Math.sin(angle) * planets.get(i).gravrate;
}
}
else{
if(y1 > y2){
xm -= Math.cos(angle) * planets.get(i).gravrate;
ym -= Math.sin(angle) * planets.get(i).gravrate;
}else{
xm += Math.cos(angle) * planets.get(i).gravrate;
ym += Math.sin(angle) * planets.get(i).gravrate;}
}
}
}
我很快就写出来了,看看使用直线的斜率而不是那个奇怪的 atan2 方程是否会有所帮助。显然它做到了。在本节中,我还使代码更具可读性。
【问题讨论】:
-
@asphere8--
atan很有可能让你伤心。我在几个应用程序中一直在努力解决它。仔细阅读 Javadoc 以确保获得所需的内容。有两种atan方法:一种带有您正在使用的 2 个参数,一种只有一个。切换可能会付出代价。我将尝试找出我的问题并分享它。那是不久前的事了。 -
我对@987654327@ 的不满实际上是复数的“参数”(三角角),但它们与平面中的位置相距不远。我最终不得不编写自己的函数来完成我无法使用任一版本的
atan完成的事情。鉴于您的数学自我描述,您可能会发现 this article 不合适,但它描述了典型atan函数的返回结果。请注意在文本中,尤其是在第 2 页和第 3 页的表格中对 pi 和 pi/2 的捏造。 -
请注意,我已经草率地得出结论,但它所基于的经验也可能会惹恼其他人。我没有研究过你的代码。可能是方程式的其他方面搞砸了。然而,由于代码通常有效,这似乎更可能是
atan滥用的症状,而不是错误的等式。 -
“问题方程式”末尾的
+1是什么? -
另外,为什么要除以 pi?
标签: java 2d game-physics gravity orbital-mechanics