0
$\begingroup$

I'm creating an orbit simulator and my planet is moving in odd elliptical orbits that aren't closed. First of all, is this even correct? Second of all, even if it is, how must I change the parameters to generate a closed orbit and what are the prerequisites for one. Here is my simple code in Java:

        float deltaX = planet.getPos().x - this.pos.x;
        float deltaY = planet.getPos().y - this.pos.y;
        float alpha = (float) Math.toDegrees(Math.atan2(deltaY, deltaX));

        float distance = (float) Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));
        float F = G * this.m * planet.getM() / distance * distance;
        this.force.x = F * MathUtils.cosDeg(alpha);
        this.force.y = F * MathUtils.sinDeg(alpha);

        this.vel.x += (this.force.x / this.m) * deltaTime;
        this.vel.y += (this.force.y / this.m) * deltaTime;

        this.pos.x += this.vel.x * deltaTime;
        this.pos.y += this.vel.y * deltaTime;

The math is basically me getting the main force of the two planets with $F = G* {m*M \over r^2}$ and using simple trigonometry I solve for the $x, y$ coordinates because I am in a 2D coordinate system.

Here are the parameters I feed the planets:

        planet1 = new Planet(20, 1, 800, 450); # r=20, m=1, pos=800, 450
        planet1.setVel(new Vector2(0, 200));
        planet2 = new Planet(40, 332000, 400, 450); # r=40, m = 332000, pos = 400, 450

(ignore the fact the lines are not in the same position as the planet but they are the correct orbit) I've researched a little and apparently its called a rosetta orbit? But yeah, I don't know how to get an elliptical closed orbit. I have managed to get a circular orbit however. enter image description here

$\endgroup$
1

1 Answer 1

1
$\begingroup$

Your issue is order of operations.

float F = G * this.m * planet.getM() / distance * distance;

Should be

float F = G * this.m * planet.getM() / (distance * distance);

The former gives you Constant Gravity, instead of Inverse-square gravity, resulting in the rosette orbit.

$\endgroup$
3
  • $\begingroup$ well that wasn't very smart of me, thank you it worked $\endgroup$
    – eisa.exe
    Jul 19, 2022 at 12:12
  • $\begingroup$ The orbit isn't fully closed though? It keeps getting smaller $\endgroup$
    – eisa.exe
    Jul 19, 2022 at 14:55
  • $\begingroup$ @eisa.exe I imagine that's probably to do with the size of your chosen deltaTime and floating point issues. PM 2Ring's comment on the initial question links to an answer that discusses those. $\endgroup$
    – notovny
    Jul 19, 2022 at 15:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.