How do I setup the esc key to exit Godot Application?
Asked Answered
H

2

7

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?

Hydrozoan answered 19/4, 2017 at 23:46 Comment(0)
H
13

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

extends Node2D

func _ready():
    set_process(true)

func _process(delta):
   if Input.is_action_pressed("key_exit"):
      get_tree().quit()
Hydrozoan answered 20/4, 2017 at 1:7 Comment(0)
P
1

According to Godot's Q&A, with Godot 3.1+, the good way to do it is:

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

It works for me with Godot 4.1.

According to Sending your own quit notification you also need

get_tree().root.propagate_notification(NOTIFICATION_WM_CLOSE_REQUEST)

before it, but I could not check it, in my trivial sample code.

Physiotherapy answered 23/10, 2023 at 10:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.