Tag Archives: input

LWJGL Input

By the end of this tutorial you will have learned how you can receive and process LWJGL input.

Everything is static

Similarly to the Display creation, the Lightweight Java Game Library input API is static.

Polling versus event queue

There are two forms of input handling. Either check the state at the current moment in time (polling) or read events from the event queue. The first method is preferred for movement with the arrow keys or the mouse, while the second method is preferable for when a key is briefly pressed to activate a power-up or click on a menu using the left mouse button.

This graph illustrates the difference between polled and event-driven input. While polled input gives out a signal as long as the button is pressed, the event-driven input only gives out a signal once for every time a button is pressed or released.

Polled LWJGL input

The following code demonstrates polled input.

if (Keyboard.isKeyDown(Keyboard.KEY_LEFT)) {
	player.moveToLeft();
}

Event-driven LWJGL input

The following code demonstrates event-driven input.

while(Keyboard.next()) {
	if (Keyboard.isKeyDown(Keyboard.KEY_SPACE)) {
		jump();
	}
	if (Keyboard.isKeyDown(Keyboard.KEY_F)) {
		pickUpItem();
	}
}

Replace Keyboard with Mouse and ‘isKeyDown’ with ‘isButtonDown’ and the same applies to the mouse input.¬†Use ‘Mouse.getX()’ and ‘Mouse.getY()’ to retrieve the coordinates of the mouse in a non-event-driven style. Similarly, you can use ‘Mouse.getDX()’ and ‘Mouse.getDY()’ to retrieve the displacement over the x-axis or the y-axis. Please note that to retrieve the correct y-coordinate with the projection matrix we created last tutorial, you need to call ‘Display.getHeight() – Mouse.getY() – 1′. If you use ‘Mouse.getDY()’ prefix it by ‘-‘. If this step is omitted, the y-value will be the opposite of the correct value.

Conclusion

That concludes this tutorial. Should you have any questions or remarks, please leave them in the comments section below.