How do I setup the esc key to exit the program?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Oliver_M
:warning: Old Version Published before Godot 3 was released.

Total newb here, I have a question about something I’m getting stuck on with a new 2D project. I added a sprite background and it shows no problem when I run the test. I setup the esc key as “key_exit” in the Input Map. Then I created a node2D as the root and added the following script to it:

extends Node2D

func _ready():
   if Input.is_action_pressed("key_exit"):
      get_tree().quit()

It doesn’t work. I’m trying to create a simple loop that listens for esc key presses and quits when I press the escape key. If I add get_tree().quit() without the if condition, it quits as soon as it starts. How do I get it to “listen” for my if condition? What am I doing wrong here?

:bust_in_silhouette: Reply From: Oliver_M

I figured it out. I was able to get it working with:

extends Node2D

func _ready():
    set_process(true)

func _process(delta):
   if Input.is_action_pressed("key_exit"):
      get_tree().quit()

One of the RARE questions I CAN answer and you beat me to it :slight_smile:

Robster | 2017-04-20 03:35

Checking for input event (set_process_input(true) in godot 2) should work too, just changes to event.is_action_pressed inside _input.

Gamefromscrtatch tutorials and official docs have examples of the ways to handle user inputs.

eons | 2017-04-20 03:52

The ESC key is mapped to ui_cancel in godot 3.
Look in Project Settings on the Input Map tab

digitorus | 2017-11-12 21:40

:bust_in_silhouette: Reply From: kthrosenberg

I know this has already been answered, but if anyone is looking for an up-to-date solution that works with 3.1+ and deals with Node lifecycle via _input rather than _process, here is the quick snippet:

func _input(event):
	if Input.is_action_pressed("ui_cancel"):
		get_tree().quit()

Thanks to @digitorus for talking about ui_cancel.

This should be now the Best Answer, yo.

animanoir | 2021-12-05 18:20

:bust_in_silhouette: Reply From: LuisArnold

Solution compatible with Godot 4:

func _input(event):
	if event is InputEventKey and event.pressed:
		if event.keycode == KEY_ESCAPE:
			get_tree().quit()

Godot Engine: Keyboard events