Godot Keyboard and Mouse Button Input Programming

Commonly you will want your Godot game to respond to user input from the keyboard and mouse. In this tutorial we will look at how to poll the inputs and to detect key presses and mouse button clicks.

The Input class is provided by Godot and provides useful methods to examine the state of keys and mouse buttons. For example we may check if a key is being pressed, or was just pressed, or just released depending on if we want to have a continuous action such as moving or a single action such as quitting the game.

Here are some of the useful methods that we may use:

godot input map

A key is an integer code for a key such as 42 for the asterisk key. However there are enumerated constants that we may use for better readability such as KEY_ASTERISK.

Regularly checking the key press state in a loop is called polling and we do this every frame from our game loop. Here is example programming code showing how it is done from the _process(delta) function:

extends Node2D

var count: int = 0

func _process(delta):
	if (Input.is_action_just_pressed("ui_accept")):
		# Print to Output window
		print("Key down")
	if (Input.is_action_just_released("ui_accept")):
		print("Key up")
	if (Input.is_action_pressed("ui_up")):
		count += 1
		print(count)
	if (Input.is_key_pressed(KEY_F)):
		var fps = 1.0 / delta
		print("FPS: %d" % fps)
	if (Input.is_mouse_button_pressed(BUTTON_LEFT)):
		print("Left mouse button pressed!")
	if (Input.get_mouse_button_mask() == 0x03):
		print("Left and right mouse buttons pressed!")
	if (Input.is_key_pressed(KEY_ESCAPE)):
		get_tree().quit()
	return delta
	

So you can see that it is quite straightforward to poll the state of the keyboard and mouse buttons and take action accordingly.

The other way to handle user input is Event Handling.

More solutions