Below is an image of my gameworld. As we can see, the player starts at position 0. each cell represents 1 game world unit. My goal is to get the player to move 1 unit (the red cell) in 1 second in 'real world' time using the LIBGDX framework.
LibGDX uses something called 'continuous rendering' by default, which means its 'main loop' runs as fast as the underlying OS is able to. The range could be anywhere from 0-80 frames per second. I am capping the FPS to 60 with the below 'main' loop (In LIbGDX the main loop is called render)
@Override
public void render(float deltaTime) {
/*
* Get the time it took to render the last frame and make sure our delta
* time is never larger than 0.0166666666666667 (60 FPS). This will
* ensure that on fast OS the game at only 60 FPS.
*/
float dt = Math.min(Gdx.graphics.getDeltaTime(), 1 / 60f);
// **********************UPDATE*********************
player.update(dt);
// ************************RENDER********************
// clear the screen and set it to cornflower blue
Gdx.gl.glClearColor(0x64 / 255.0f, 0x95 / 255.0f, 0xed / 255.0f,
0xff / 255.0f);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
worldRenderer.render();
}
Below is the code for my player object's update method. As we can see it is operating solely on the delta time for now. In a perfect world of 60 FPS, this would work perfectly but unfortunatly FPS dips will always happen (especially on mobile platforms). How can I add a calculation on top of the delta time to move the player 1 unit in real time regardless of framerate?
@Override
public void update(float deltaTime) {
// handle user input **always should come first**
if (Gdx.input.isKeyPressed(Keys.SPACE)) {
position.x += deltaTime;
}
}
Below shows what is happening with my current code, if we had a perfect 60 FPS the position should = 1, but as we can see it does not because the FPS varies slightly from frame to frame.