Opening something with a keyboard button

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Godot_coding

I just started godot and I have a problem. I have made a 2D game and for example I want to add an inventory. But i want the inventory to open every time the player presses the button “e” or “i”. How can I do this??

:bust_in_silhouette: Reply From: DaddyMonster

You can do this in a few steps:

Bind the key:

Click “Project” (at the top menu bar), then “project settings” on the dropdown and then go to the “input map” tab. In the “Action” field give your action a name (eg “open_menu”) and click “Add”. Then find it at the bottom of the list and click the “+”, selected “key” and press the key you want to bind.

Make a scene

No, not like at the office xmas party. :wink: On the tab above the panel click “+”. Click “Other Node” and now make your menu tree. You might want a “Control” node, “NinePatchRect”, whatever works for you. On the menu bar select “scene” and “Save Scene as”, give it a name / folder.

Add a key press event

Let’s add a script to your “World” scene (whichever scene runs by default). Right click on the root node (top left) and select “Attach Script”.

In this script you need a reference to your scene. You can do this like this as a member variable (not in a method):

var menu_scene = preload()

In the brackets you put the path to your scene. You can literally drag it from the bottom left to the brackets and it will autocomplete for you or you can pick it from the dropdown.

The let’s add the action.

var is_menu_open = false

func _input(event):
    if event.is_action_pressed("open_menu"):
        is_menu_open = not is_menu_open

func toggle_menu():
    if not is_menu_open:
       var menu = menu_scene.instance()

Good luck!

Omg thank you so much this is very useful. Have a nice day!!

Godot_coding | 2022-01-04 23:06