Search code examples
javaandroidlibgdx

Java LibGDX Update and Draw Methods


People usually write "draw(SpriteBatch batch)" and "update(float deltaTime)" methods in their player classes. Why don't they just write "render(SpriteBatch batch, float deltaTime)"? Because of readability? I mean, why they make two methods? They can do in single method.


Solution

  • Readability and ease of updating/changing is one reason.

    But there are also logistical reasons. You want to be sure your whole game state is fully up to date before you start drawing, so whatever is on screen is as up-to-date as possible. If you put updating and rendering into one method for each object, then objects that are updated and drawn first might look out of date compared to objects that are updated later and affect the state of the earlier objects. But if updating and drawing are separated, you can update the entire game and then draw the entire game.

    And if your game uses physics, the separation of updating and drawing allows you to update your world at a fixed timestep (at a different rate as the drawing) to ensure the game play is not affected by frame rate.