libGDX most important method and how to use it

Contents

Understand render method

The render method is perhaps one of the most important method in libGDX. While the game is running, all drawing and displaying tasks are executed within this method. The render method gets called repeatedly by libGDX at a frequency of about 60 to 80 times per second, depending on the machine’s speed.

A typical set of instructions in render method usually look like this:


    public void render() {
        // 1. Clear the screen

        // 2. Update objects states over time 
        // (for example: positions, rotation, opacity, color, etc)

        // 3. Draw objects with updated states
    }

Each time render is called, the screen is cleared and all previous drawings are discarded (1). Then, each object’s state is updated to new values (2). The amount of value change usually depends on the time difference between method calls. Finally objects are drawn on the screen to reflect those changes (3).

The continuous change of object states that get drawn on the screen is what creates the movement of objects. In traditional frame-by-frame animation, each render call is essentially a drawing on a separate frame

Most of the time your task will involve managing object states such as storing, updating, deleting those states over time.

Detect user interaction

Another usage of render method is to detect user interaction in the game. Either mouse or touch and keyboard input can be detected and extra details can be revealed in render method such as the last touch positions or the key that is just pressed


    public void render() {
		// Detect pressed key, carry out actions if the key 'A' was pressed
        if (Gdx.input.isKeyJustPressed(Input.Keys.A)) {
			System.out.println("Key A is just pressed");
		};
		// Detect mouse/touch position, report on screen
        if (Gdx.input.justTouched()) {
			System.out.println("Last touch position "
					+ Gdx.input.getX() + " "
					+ Gdx.input.getY());
		}
    }

Render state vs scene graph

Unlike other frameworks that use scene graph techniques to create a hierarchy of nodes, where each node is a displayable object or a container, libGDX doesn’t have such implementation. Instead, you manage your own rendering state, which consists of a collection of objects and the logic to mutate those states.

This may complicate the code due to the lack of abstraction, but it offers a significant performance advantage because the engine doesn’t have to recursively traverse a tree of nodes to render the scene. Ultimately, you control what to draw and display, and what to discard on every frame, which may result in a boost in rendering speed and performance.

libGDX does have a Scene2D UI package, but it is primarily used to create user interfaces, which will be discussed in another article.