Skip to content
Advertisement

Planets won’t render when using for-loop in libgdx

I am running an N-body simulation (testing with three planets at first) and it appears when I use a for-loop to do so, all of the planets don’t render and while debugging i found out they don’t even have an address. However, if I manually type in the movement of all three planets it works. Here’s my code:

    public MainScreen(final Application application) {
        this.application = application;
        planets = new ArrayList<>();

        cam = new OrthographicCamera(WIDTH, HEIGHT);
        batch = new SpriteBatch();

        planet1 = new Planet(40, 1, 700, 450); // params consist of (r, m, x, y) in that order
        planet1.setVel(new Vector2(0, 400));
        planet2 = new Planet(80, 333000, 400, 450);
        planet3 = new Planet(20, 1, 200, 450);
        planet3.setVel(new Vector2(0, 400));

        planets.add(planet2);
        planets.add(planet1);
        planets.add(planet3);

    }    


public void render(float delta) {
        ScreenUtils.clear(0, 0, 0, 1);
        batch.setProjectionMatrix(cam.combined);


        batch.begin();
        planet1.render(batch);
        planet2.render(batch);
        planet3.render(batch);
        cam.position.set(planet2.getPos().x + planet2.getR(), planet2.getPos().y + planet2.getR() - 30, 0);
        cam.update();
        batch.end();

        for(int i = 0; i < planets.size(); i++) {
            for(int j = 0; j < planets.size(); j++) {
                planets.get(i).move(Gdx.graphics.getDeltaTime(), planets.get(j));
            }
        }
    }

It leaves them unrendered. However if I do the following it works:

planet1.move(Gdx.graphics.getDeltaTime(), planet2);
planet1.move(Gdx.graphics.getDeltaTime(), planet3);
planet2.move(Gdx.graphics.getDeltaTime(), planet1);
planet2.move(Gdx.graphics.getDeltaTime(), planet3);
//... etc

Advertisement

Answer

Since you’re not doing any rendering in the loop, I’m guessing you’re doing something to their positions that moves them out of view of the camera. Shouldn’t you be checking if (i != j) in your loop? I’m assuming you don’t want a planet to be affected by itself in the move function.

    for(int i = 0; i < planets.size(); i++) {
        for(int j = 0; j < planets.size(); j++) {
            if (i == j) continue;
            planets.get(i).move(Gdx.graphics.getDeltaTime(), planets.get(j));
        }
    }

By the way, usually you update the simulation before rendering, or else your visuals are always lagging the physics by one frame.

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