Cruise Game 08 · Add arrow-key controls

Midnight Deck Dash · Lesson 08 of 50 · Beginner · About 30 min

The bridge’s training computer has a keyboard. Players can now use arrows for practice as well as screen controls for mobile.

A straight teak promenade with a cream cabin wall on one side and a ship railing above the moonlit ocean on the other.
What you’ll make Route four arrow keys into the same movement rule used by the screen buttons.

Download the projects from the course page. In Godot’s Project Manager, choose Import, select project.godot, and use Run Project (F5). Start from checkpoints/07 when the lesson builds on prior work, or copy the checkpoints/08 folder to try this lesson on its own. Read the file names in the steps before editing.

Check the event. Use fresh key presses. → Match the arrow. Choose a direction vector. → Call one movement rule. Buttons and keys obey the same rails.
Check the event → Match the arrow → Call one movement rule
Godot checkpoint window for Add arrow-key controls
From the running Godot checkpoint.

Build it step by step

Language and tools in this lesson InputEvent, InputEventKey, is, _unhandled_key_input, pressed, echo, match, fallback.

  1. Keep one movement function

    Open main.gd from Lesson 7 and retain _try_move. Add _unhandled_key_input at the far left below the existing functions.

    Why it works Godot calls this handler when a key event remains after the interface has had a chance to use it. It can call the same rule as the buttons.

  2. Check the input type first

    Type the input header and its two-line type guard. Indent return beneath if.

    func _unhandled_key_input(event: InputEvent) -> void:
    	if not event is InputEventKey:
    		return

    Why it works is checks which kind of object arrived. Returning for other kinds keeps the handler from reading a property that belongs to keyboard input.

  3. Handle fresh key presses

    After the type check, stop when the key has been released or the event is an echo.

    	if not event.pressed or event.echo:
    		return

    Why it works An echo is a repeat while a key is held. Ignoring released and repeated keys keeps movement turn by turn.

  4. Match a direction

    Add the match and its four named cases. Place _try_move one indent below each case and give the default underscore branch an early return.

    	match event.keycode:
    		KEY_UP:
    			_try_move(Vector2i.UP)
    		KEY_LEFT:
    			_try_move(Vector2i.LEFT)
    		KEY_RIGHT:
    			_try_move(Vector2i.RIGHT)
    		KEY_DOWN:
    			_try_move(Vector2i.DOWN)
    		_:
    			return

    Why it works One matching key runs one movement call. The underscore branch catches unrelated keys and leaves the courier alone.

  5. Tell Godot the event has been used

    Put set_input_as_handled after the match, at the same indentation as match itself.

    	get_viewport().set_input_as_handled()

    Why it works After an arrow key moves or hits a rail, the viewport marks that event as handled. Key cases that returned early skip this line.

  6. Compare the two input paths

    Run and click the game area if it needs focus. From (0, 0), press Right then use the South button. Restart and use East then Down. If a focused button uses arrows for navigation, select the deck area before testing again.

    Why it works Each route reaches the same movement function, so the player should see the same final address.

Watch the values change

  1. Press Right from the corner The fresh input has the KEY_RIGHT code.
    What you see. The match tries a move of (1, 0).
  2. Tap South The button’s remembered vector is (0, 1).
    What you see. The move reaches (1, 1).
  3. Press an unrelated key The code reaches the fallback branch.
    What you see. The address stays (1, 1).

Predict before you run Is the rail rule different when you press Up at (0, 0) instead of tapping North?

Reveal the answer

No. Both call _try_move with Vector2i.UP, which proposes and rejects (0, -1).

Complete checkpoint

Arrow keys and buttons move one tile at a time and the rail check works for both.

main.gd

extends Control

const BOARD_ORIGIN := Vector2(40, 124)
const TILE_SIZE := 76
const DECK_SIZE := Vector2i(7, 5)
const OCEAN := Color("#0b2137")
const BRASS := Color("#f2bc64")
const INK := Color("#07111e")
var player_cell := Vector2i.ZERO
var sign: Label

func _ready() -> void:
	sign = Label.new()
	sign.position = Vector2(40, 47)
	sign.add_theme_font_size_override("font_size", 28)
	add_child(sign)
	_refresh_log()
	_add_direction("North", Vector2(679, 171), Vector2i.UP)
	_add_direction("West", Vector2(607, 233), Vector2i.LEFT)
	_add_direction("East", Vector2(751, 233), Vector2i.RIGHT)
	_add_direction("South", Vector2(679, 295), Vector2i.DOWN)

func _refresh_log() -> void:
	sign.text = "Promenade | Courier at (%d, %d)" % [player_cell.x, player_cell.y]

func cell_centre(cell: Vector2i) -> Vector2:
	return BOARD_ORIGIN + Vector2(cell) * TILE_SIZE + Vector2.ONE * (TILE_SIZE / 2.0)

func _draw() -> void:
	draw_rect(Rect2(Vector2.ZERO, get_viewport_rect().size), OCEAN)
	for row in range(DECK_SIZE.y):
		for column in range(DECK_SIZE.x):
			var cell := Vector2i(column, row)
			var top_left := cell_centre(cell) - Vector2.ONE * (TILE_SIZE / 2.0)
			var tile := Rect2(top_left + Vector2.ONE * 2.0, Vector2.ONE * (TILE_SIZE - 4.0))
			draw_rect(tile, Color("#16445a"))
	draw_circle(cell_centre(player_cell), 20.0, BRASS)
	draw_circle(cell_centre(player_cell), 7.0, INK)

func _add_direction(caption: String, at: Vector2, delta: Vector2i) -> void:
	var button := Button.new()
	button.text = caption
	button.position = at
	button.custom_minimum_size = Vector2(122, 52)
	button.pressed.connect(_try_move.bind(delta))
	add_child(button)

func _try_move(delta: Vector2i) -> void:
	var next_cell := player_cell + delta
	if not _inside(next_cell):
		sign.text = "Rail ahead | Courier stays at (%d, %d)" % [player_cell.x, player_cell.y]
		return
	player_cell = next_cell
	_refresh_log()
	queue_redraw()

func _inside(cell: Vector2i) -> bool:
	return cell.x >= 0 and cell.x < DECK_SIZE.x and cell.y >= 0 and cell.y < DECK_SIZE.y

func _unhandled_key_input(event: InputEvent) -> void:
	if not event is InputEventKey:
		return
	if not event.pressed or event.echo:
		return
	match event.keycode:
		KEY_UP:
			_try_move(Vector2i.UP)
		KEY_LEFT:
			_try_move(Vector2i.LEFT)
		KEY_RIGHT:
			_try_move(Vector2i.RIGHT)
		KEY_DOWN:
			_try_move(Vector2i.DOWN)
		_:
			return
	get_viewport().set_input_as_handled()

GDScript line by line

Follow the line numbers, including the indent at the start of each line. Find the code the game will run first, then look for the function that reacts when you tap or change something.

Read main.gd line by line
  1. extends ControlGives the root of this lesson the positioning and sizing features of a Godot Control, which is the type created by choosing User Interface in the scene editor.
  2. const BOARD_ORIGIN := Vector2(40, 124)Defines the board’s top-left pixel position. All tile drawing starts relative to these two coordinates.
  3. const TILE_SIZE := 76Defines the width and height of one square tile in pixels. A move of one cell means a shift of 76 pixels in the drawing.
  4. const DECK_SIZE := Vector2i(7, 5)Defines seven columns and five rows. With zero-based addresses the last tile is (6, 4).
  5. const OCEAN := Color("#0b2137")Names the dark blue background colour. The hash sits inside a colour string here, so it is not a GDScript comment.
  6. const BRASS := Color("#f2bc64")Names the gold used by the courier and cargo art from a hex colour triplet.
  7. const INK := Color("#07111e")Names the dark colour used to draw smaller shapes on top of the gold for contrast.
  8. var player_cell := Vector2i.ZEROPlaces the courier at (0, 0), the upper-left cell, which touches the north and west safety rails.
  9. var sign: LabelDeclares a script-wide reference with the Label type. _ready fills it, and other functions can then update the same on-screen label.
  10. func _ready() -> void:Godot calls this method after the scene is ready. Its indented steps make the dispatch label and any controls before the player can use them. It does not return a value.
  11. sign = Label.new()Makes the label and saves it to the script-wide sign variable. This line uses assignment without var so it does not create a second, local variable named sign.
  12. sign.position = Vector2(40, 47)Places the address readout near the top of the practice window, 40 pixels from the left and 47 down.
  13. sign.add_theme_font_size_override("font_size", 28)Makes the coordinate readout 28 points tall using a font size override for this particular Label.
  14. add_child(sign)Adds the Label to this node so it becomes part of the active scene and Godot can display its text.
  15. _refresh_log()Rebuilds the address text from the current position. A later move or reset calls the same helper after it changes player_cell.
  16. _add_direction("North", Vector2(679, 171), Vector2i.UP)Creates the North button at the given pixel position and stores the (0, -1) direction, which will subtract one from the row when pressed.
  17. _add_direction("West", Vector2(607, 233), Vector2i.LEFT)Creates the West button at the given pixel position and stores the (-1, 0) direction, which will subtract one from the column when pressed.
  18. _add_direction("East", Vector2(751, 233), Vector2i.RIGHT)Creates the East button at the given pixel position and stores the (1, 0) direction, which will add one to the column when pressed.
  19. _add_direction("South", Vector2(679, 295), Vector2i.DOWN)Creates the South button at the given pixel position and stores the (0, 1) direction, which will add one to the row when pressed.
  20. func _refresh_log() -> void:Defines where the courier’s position is converted into readable text. Keeping it here gives setup, movement and reset a shared update.
  21. sign.text = "Promenade | Courier at (%d, %d)" % [player_cell.x, player_cell.y]Builds the position text with x as the column first and y as the row second. Both coordinates are whole numbers.
  22. func cell_centre(cell: Vector2i) -> Vector2:Converts a grid address to a pixel position. The input cell has whole numbers, and the Vector2 result can represent fractional pixels.
  23. return BOARD_ORIGIN + Vector2(cell) * TILE_SIZE + Vector2.ONE * (TILE_SIZE / 2.0)Multiplies the column and row by the tile size, adds the board’s pixel origin, then moves half a tile across and down. For (2, 1), that yields (230, 238).
  24. func _draw() -> void:Godot calls this drawing method when the canvas needs a frame. Earlier drawing lines appear under later lines.
  25. draw_rect(Rect2(Vector2.ZERO, get_viewport_rect().size), OCEAN)Paints the dark blue behind the whole viewport. Rect2 combines a top-left point and a size.
  26. for row in range(DECK_SIZE.y):Repeats the nested drawing instructions for rows 0–4. The upper bound of range is excluded.
  27. for column in range(DECK_SIZE.x):Repeats tile drawing for columns 0–6 inside the current row. Each new row begins again at column 0.
  28. var cell := Vector2i(column, row)Creates the tile address for this loop iteration. The x part receives column and the y part receives row.
  29. var top_left := cell_centre(cell) - Vector2.ONE * (TILE_SIZE / 2.0)Subtracts half the tile width from both axes to convert the centre point back to its upper-left corner.
  30. var tile := Rect2(top_left + Vector2.ONE * 2.0, Vector2.ONE * (TILE_SIZE - 4.0))Starts the painted square two pixels inside the tile and subtracts four pixels from its size, giving a two-pixel margin on each edge.
  31. draw_rect(tile, Color("#16445a"))Paints the current walkway tile. The nested loops run this once per tile before the courier is drawn.
  32. draw_circle(cell_centre(player_cell), 20.0, BRASS)Draws one brass circle at the courier’s current pixel centre with a 20-pixel radius.
  33. draw_circle(cell_centre(player_cell), 7.0, INK)Adds a dark inner circle at the same centre. Drawing a smaller circle after the brass one produces the ring effect.
  34. func _add_direction(caption: String, at: Vector2, delta: Vector2i) -> void:Creates one direction button. The arguments carry its visible text, its pixel placement and the direction it will use when pressed.
  35. var button := Button.new()Creates a new Godot Button in memory. Each call to the builder creates a separate Button.
  36. button.text = captionShows the caller’s text, such as East, on the button face.
  37. button.position = atPlaces the control at the pixel address passed in by the call that created it.
  38. button.custom_minimum_size = Vector2(122, 52)Gives each direction button a 122-by-52-pixel target so it is easier to tap.
  39. button.pressed.connect(_try_move.bind(delta))Connects the pressed signal to the movement function. bind saves this button’s direction as the argument to pass at tap time.
  40. add_child(button)Attaches the Button to the scene so that Godot can draw it, give it input and emit its signal when pressed.
  41. func _try_move(delta: Vector2i) -> void:Handles a one-cell movement request from any direction button or arrow key. Each call receives the requested coordinate change.
  42. var next_cell := player_cell + deltaCalculates the newly requested address in a separate variable. The current cell stays the same until the guards approve the move.
  43. if not _inside(next_cell):Checks for an off-deck address. The indented warning and early return run only when a rail blocks the requested move.
  44. sign.text = "Rail ahead | Courier stays at (%d, %d)" % [player_cell.x, player_cell.y]Prints the rail warning with the address the courier still occupies, which might differ from the proposed next_cell.
  45. returnLeaves the current function immediately. The later position update is skipped if this early exit belongs to a blocked movement check.
  46. player_cell = next_cellCommits the approved position after the guard checks. The refresh and repaint that follow can now read the new cell.
  47. _refresh_log()Rebuilds the address text from the current position. A later move or reset calls the same helper after it changes player_cell.
  48. queue_redraw()Asks Godot to repaint. The _draw method will read the current player_cell when Godot performs the redraw.
  49. func _inside(cell: Vector2i) -> bool:Answers whether the proposed address fits this deck. The caller receives true or false.
  50. return cell.x >= 0 and cell.x < DECK_SIZE.x and cell.y >= 0 and cell.y < DECK_SIZE.yRequires non-negative x and y, with each coordinate smaller than the count for that axis. In a seven-by-five grid, column seven and row five are already outside.
  51. func _unhandled_key_input(event: InputEvent) -> void:Receives keyboard events the interface did not already use. The event object stores which key changed and whether this is an ordinary press, release or repeat.
  52. if not event is InputEventKey:Keeps the rest of the handler limited to keyboard events, whose specific properties the next checks read.
  53. returnLeaves the current function immediately. The later position update is skipped if this early exit belongs to a blocked movement check.
  54. if not event.pressed or event.echo:Filters out released keys and repeat events caused by holding a key. Either condition is enough to stop this call.
  55. returnLeaves the current function immediately. The later position update is skipped if this early exit belongs to a blocked movement check.
  56. match event.keycode:Chooses the branch for the key number. Each arrow case passes its direction to _try_move, where the game validates it.
  57. KEY_UP:Matches only the Up arrow, the input for requesting one cell north.
  58. _try_move(Vector2i.UP)Requests North with the vector (0, -1), which will subtract one from the row if the move is legal.
  59. KEY_LEFT:Matches only the Left arrow, the input for requesting one cell west.
  60. _try_move(Vector2i.LEFT)Requests West with the vector (-1, 0), which will subtract one from the column if the move is legal.
  61. KEY_RIGHT:Matches only the Right arrow, the input for requesting one cell east.
  62. _try_move(Vector2i.RIGHT)Requests East with the vector (1, 0), which will add one to the column if the move is legal.
  63. KEY_DOWN:Matches only the Down arrow, the input for requesting one cell south.
  64. _try_move(Vector2i.DOWN)Requests South with the vector (0, 1), which will add one to the row if the move is legal.
  65. _:Catches any key not listed above. The fallback returns without moving the courier.
  66. returnLeaves the current function immediately. The later position update is skipped if this early exit belongs to a blocked movement check.
  67. get_viewport().set_input_as_handled()Marks an arrow request as used after processing it. An unrecognised key returns earlier and skips this instruction.

Find and fix a bug

If arrows do nothing, click within the game window, release the arrow, then press again. Check the exact function name _unhandled_key_input.

Try a change

Add WASD options in a copy. A match case such as KEY_RIGHT, KEY_D: lets both keys use the same block.