Skip to content
Advertisement

Orbit Simulator in Java returning odd values for velocity etc. despite correct math

I am using LibGDX to make an orbit simulator (elliptical as planets possess their own initial velocity) and I have the physics mapped out like so:

    public void move(float deltaTime, Planet planet) {

        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.cos(alpha);
        this.force.y = F * MathUtils.sin(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 problem is that my planet wobbles around and doesn’t orbit at all. I fear my calculations in the code might be wrong as the physics are definitely double-checked and correct.

Each celestial object is a planet and I have no ‘Sun’ classes of any type so far. Only one Planet class, which only has Getter and Setter methods, a render() method (which seems irrelevant) and the presented move() method.

I find nothing necessitates the following however I will add the parameters’ values I chose for the both planets:

        planet1 = new Planet(30, 1, new Vector2(300, 300));
        planet2 = new Planet(70, 332000, new Vector2(400, 400));

I am also aware LibGDX won’t have the x, y coordinates of my circle in the middle but rather the bottom left. Therefore I have modified that in the constructor:

        this.pos = pos;
        this.pos.x -= r;
        this.pos.y -= r;

Advertisement

Answer

I have been messing around and debugging the code and realised it was a very minor mistake, a classic mistake to assume that the math library’s cos() and sin() functions use degrees. They don’t. They use radians and that was the whole problem all along.

Instead of:

        this.force.x = F * MathUtils.cos(alpha);
        this.force.y = F * MathUtils.sin(alpha);

One must do:

        this.force.x = F * MathUtils.cosDeg(alpha);
        this.force.y = F * MathUtils.sinDeg(alpha);

I will make sure to edit the question to emphasize this problem and solution for future viewers of it.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement