我正试图在所有物体之间实施引力。所有尝试实现类似的东西都会导致对象的奇怪行为。这是我实现的代码的一个版本。它不起作用:
public void updateGravitation() {
for (GravitationalBody aGravitationalBody : gravitationalBodies){
double sumX = 0;
double sumY = 0;
for (GravitationalBody bGravitationalBody : gravitationalBodies){
if (aGravitationalBody != bGravitationalBody) {
double massMultiplication = aGravitationalBody.getMass() * bGravitationalBody.getMass();
double distanceX = aGravitationalBody.getPosition().x - bGravitationalBody.getPosition().x;
double distanceY = aGravitationalBody.getPosition().y - bGravitationalBody.getPosition().y;
double r = Math.sqrt(Math.pow(distanceX,2) + Math.pow(distanceY,2));
double force = G * massMultiplication/(r * r);
double theta = distanceY / distanceX;
sumX += force * theta;
sumY += force * theta;
}
}
aGravitationalBody.appleForce(sumX,sumY);
}
}
我做错了什么?
PS新年快乐!
PSS抱歉英语不好。
答案 0 :(得分:1)
谢谢Margaret Bloom。我将代码更改为:难道你不觉得力的X-Y分量始终相等吗?再想一想distanceY / distanceX
public void updateGravitation() {
for (GravitationalBody aGravitationalBody : gravitationalBodies){
double sumX = 0;
double sumY = 0;
for (GravitationalBody bGravitationalBody : gravitationalBodies){
if (aGravitationalBody != bGravitationalBody) {
double massMultiplication = aGravitationalBody.getMass() * bGravitationalBody.getMass();
double distanceX = aGravitationalBody.getPosition().x - bGravitationalBody.getPosition().x;
double distanceY = aGravitationalBody.getPosition().y - bGravitationalBody.getPosition().y;
double r = Math.sqrt(Math.pow(distanceX,2) + Math.pow(distanceY,2));
double force = G * massMultiplication/(r * r);
sumX += -1*force * distanceX/r;
sumY += -1*force * distanceY/r;
}
}
aGravitationalBody.appleForce(sumX,sumY);
}
}
现在工作正常