Navigating a menu with a keyboard?

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

Does anyone know the best way to make a menu list you can scroll with a keyboard. For example, I have a menu that has the following options:


They are sorted vertically, and I would like to sort through them using the up and down arrow keys, and then select whatever the highlighted option is with the select key ( whatever that may be in the end, we’ll say its enter for simplicity sake). I’ve been trying to implement this system on my own but it is VERY quickly becoming unwieldy. So does anyone know how to do implement this correctly?

:bust_in_silhouette: Reply From: Arc Futahito

Just have them as children of Vboxcontainer (Hboxcontainer?) and place focus on element when turn comes up.

Just out of curiosity, would I be able to make a sprite hover over these elements when they have focus? (To better show which is selected) and if so, would you be willing to give me a quick sudo code example?

FateAce | 2016-02-25 06:31

:bust_in_silhouette: Reply From: dc1a0

The way I would go about this is to store direction key presses as either boolean variables or a vector (I’d prefer vector personally,) controlled by the input function. Then, you can check what the active area is, whether it’s the main game or a menu panel, to decide how to apply the ‘direction’ keys.

In the controller function.

#keep a global variable
var direction = Vector2(0,0)

func _input(event):
	if event.is_action("up") and event.is_pressed():
		direction.y = -1
	elif event.is_action("down") and event.is_pressed():
		direction.y = 1
        direction.y = 0

if event.is_action("right") and event.is_pressed():
	direction.x = -1
elif event.is_action("left") and event.is_pressed():
	direction.x = 1
    direction.x = 0

in game:

#however you move (I'll use the kinematicbody2d's move for this)
    move(direction.normalized() * speed) #speed is how far you want to move per frame

in menu:

#use a variable to keep track of position in array
var list_pos = 0
#somewhere in process of the menu script
    list_pos += direction.y 

The code may not be exact as this answer is off the top of my head.