Search code examples
libgdx

Libgdx game speeding up and slowing down every second


My game is a platformer and the screen follows the player who is constantly moving right across the backround. Every second the game slows the movement right and then speeds up again. How would I stop this from happening. I have already passed delta time into my world.step but they did not help the lag or stutter. Thanks

MAIN RENDER LOOP

   public void update(float dt){
        world.step(1 / 60f, 2, 2);

        handleInput(dt);

        camX();

        player.moveMario();

        hud.update();

        gameCam.update();
        renderer.setView(gameCam);
    }

    @Override
    public void render(float delta) {
        update(delta);
        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        renderer.render();

        game.batch.setProjectionMatrix(hud.stage.getCamera().combined);
        hud.stage.draw();

        game.batch.setProjectionMatrix(gameCam.combined);
        game.batch.begin();
        game.batch.draw(ball, player.b2Body.getPosition().x - MarioBros.RADIUS_CHARACTER / MarioBros.PPM, player.b2Body.getPosition().y - MarioBros.RADIUS_CHARACTER / MarioBros.PPM, 70 / MarioBros.PPM, 70 / MarioBros.PPM);
        mapCreator.createSpikeBalls(map, animation, game.batch);
        endOfGame();
        game.batch.end();

        b2dr.render(world, gameCam.combined);
    }

    public void camX(){
            gameCam.position.x = gamePort.getWorldWidth() / 2;
            if(player.b2Body.getPosition().x  >= gamePort.getWorldWidth() / 2){
                gameCam.position.x  = player.b2Body.getPosition().x;
            }
    }

MOVE THE CHARACTER TO THE RIGHT

 public void moveMario(){
        if (b2Body.getLinearVelocity().x < 4){
            b2Body.applyLinearImpulse(new Vector2(2.7f, 0), b2Body.getWorldCenter(), true);
        }
    }

Solution

  • You didn't write anything about your world and body settings but I guess that the following happens:

    • You apply an impulse to mario => his speed increases
    • In the following few world steps, the body friction slows mario down
    • As soon as b2Body.getLinearVelocity().x < 4 is true, you again apply an impulse to mario
    • Friction slows him down again
    • ...

    Apart from that, you definitely should pass deltaTime to the world's step method