Tiny Shelf 35 · Make touch targets and keys agree

Tiny Shelf Studio · Lesson 35 of 50 · Intermediate to advanced · About 35 min

The display may be on a small phone or a computer. Give shoppers room to tap, and make the keyboard highlight the same slot.

Miniature packaging workshop with coloured paper models, tools and a teal cutting mat.
What you’ll make Map tap and arrow movement to a single shelf selection rule and reflow at narrow sizes.

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/34 when the lesson builds on prior work, or copy the checkpoints/35 folder to try this lesson on its own. Read the file names in the steps before editing.

Read intent. Click a slot or use arrows. → Choose coordinates. Send the same two values. → Clamp bounds. Keep the mark on the shelf. → Reflow buttons. Use the available width.
Read intent → Choose coordinates → Clamp bounds → Reflow buttons
Godot checkpoint window for Make touch targets and keys agree
From the running Godot checkpoint.

Build it step by step

Language and tools in this lesson Control.resized, Vector2i, InputEventKey, match, clampi, Button.pressed.

  1. Open the design bench

    Import this checkpoint's project.godot into Godot 4.7.2. Open main.gd from FileSystem. Press F5 for the starting view and F8 to stop it. Keep a copy to undo experiments.

    Why it works The checkpoint scene attaches main.gd to a Control. Each test starts from that known version, so compare one change with the original.

  2. Give each slot coordinates

    Find the nested loops. Trace the bound point for the fifth button, counting from one. Tap button 5 and compare the labels.

    var control := place_button("", Vector2.ZERO, choose.bind(Vector2i(x, y)), 48)

    Why it works The loop walks through a row before starting a new one. The fifth button sends x=0 and y=1.

  3. Reflow by available width

    Run the checkpoint in its own resizable game window, or inspect it at a temporarily smaller viewport width. Drag or change from 960 to 360 pixels and compare the button grid.

    var narrow := size.x < 550.0

    Why it works The resized signal calls layout. The threshold switches spacing, and the actual sizes stay bigger than 48 by 48 logical pixels.

  4. Clamp the selected coordinate

    Start at the top-left and press Left, Up, Right, Down. Check the status after every press.

    current = Vector2i(clampi(point.x, 0, COLS - 1), clampi(point.y, 0, ROWS - 1))

    Why it works clampi keeps x or y inside an inclusive range. An outward arrow at an edge keeps its coordinate on the edge.

  5. Route an arrow through the same function

    Follow KEY_DOWN to choose. Click slot 6, then press Down and check which slot is marked.

    choose(current + Vector2i.DOWN)

    Why it works The key gets a point by adding a direction. The click already has a point. Both call choose to enforce the same limits.

  6. Check one move per press

    Hold an arrow and compare it with quick separate presses. Remove the echo guard for one test, then restore it.

    if not event is InputEventKey or not event.pressed or event.echo:

    Why it works An echoed keyboard event comes from holding the key down. Ignoring it gives one step per fresh press.

Watch the values change

  1. Open current is (0, 0).
    What you see. Button 1 has a check. The label counts row and column from one.
  2. Tap button 6 choose receives (1, 1).
    What you see. The status shows row 2, column 2.
  3. Press Down twice The first key reaches (1, 2), and the second is clamped to that point.
    What you see. The status stays at row 3, column 2.

Predict before you run If the player is at x=3 and taps Right, what appears on the screen?

Reveal the answer

The mark stays in the last column. clampi returns 3 and choose redraws the same selection.

Complete checkpoint

A 4×3 selection grid with 12 touch buttons and the same selection behavior on arrow keys.

main.gd

extends Control

const COLS := 4
const ROWS := 3
var current := Vector2i.ZERO
var cells: Array[Button] = []
var info: Label
var headline: Label

func _ready() -> void:
	headline = label("Touch and keys", Vector2(44, 62), 33)
	label("TINY SHELF STUDIO  /  TOUCH", Vector2(44, 35), 14, GOLD)
	info = label("", Vector2(44, 113), 16, SEA)
	for y in range(ROWS):
		for x in range(COLS):
			var control := place_button("", Vector2.ZERO, choose.bind(Vector2i(x, y)), 48)
			control.focus_mode = Control.FOCUS_NONE
			cells.append(control)
	resized.connect(layout)
	layout()
	choose(Vector2i.ZERO)

func layout() -> void:
	var narrow := size.x < 550.0
	var spacing := Vector2(57.0, 67.0) if narrow else Vector2(144.0, 85.0)
	var start := Vector2(44.0, 167.0)
	for i in range(cells.size()):
		var x := i % COLS
		var y := int(floor(float(i) / COLS))
		cells[i].size = spacing - Vector2(8.0, 8.0)
		cells[i].position = start + Vector2(x, y) * spacing
	queue_redraw()

func choose(point: Vector2i) -> void:
	current = Vector2i(clampi(point.x, 0, COLS - 1), clampi(point.y, 0, ROWS - 1))
	var active := current.y * COLS + current.x
	for i in range(cells.size()):
		cells[i].text = "✓" if i == active else str(i + 1)
	info.text = "Selected row %d, column %d" % [current.y + 1, current.x + 1]

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

func _draw() -> void:
	backdrop()

const PAPER := Color("#fff4de")
const GOLD := Color("#f5bd79")
const SEA := Color("#9ddcd0")
const INK := Color("#172c3c")
const EDGE := Color("#54817f")

func title_page(unit: String, heading: String, subtitle: String) -> void:
	label("TINY SHELF STUDIO  /  " + unit, Vector2(44, 36), 14, GOLD)
	label(heading, Vector2(44, 65), 33)
	label(subtitle, Vector2(46, 119), 16, SEA)

func label(words: String, at: Vector2, pixels: int = 20, ink: Color = PAPER) -> Label:
	var item := Label.new()
	item.text = words
	item.position = at
	item.add_theme_font_size_override("font_size", pixels)
	item.add_theme_color_override("font_color", ink)
	add_child(item)
	return item

func place_button(words: String, at: Vector2, action: Callable, width: float = 170.0) -> Button:
	var control := Button.new()
	control.text = words
	control.position = at
	control.custom_minimum_size = Vector2(width, 48)
	control.add_theme_font_size_override("font_size", 17)
	control.add_theme_color_override("font_color", PAPER)
	control.add_theme_stylebox_override("normal", style(Color("#244557"), EDGE))
	control.add_theme_stylebox_override("hover", style(Color("#365a62"), SEA))
	control.add_theme_stylebox_override("pressed", style(Color("#315b56"), SEA))
	control.add_theme_stylebox_override("focus", style(Color.TRANSPARENT, GOLD, 3))
	control.pressed.connect(action)
	add_child(control)
	return control

func style(fill: Color, edge: Color, line: int = 1) -> StyleBoxFlat:
	var block := StyleBoxFlat.new()
	block.bg_color = fill
	block.border_color = edge
	block.set_border_width_all(line)
	block.set_corner_radius_all(8)
	return block

func panel(rect: Rect2, fill: Color, edge: Color = EDGE) -> void:
	draw_style_box(style(fill, edge), rect)

func backdrop() -> void:
	draw_rect(Rect2(Vector2.ZERO, size), Color("#102333"))
	panel(Rect2(22, 19, size.x - 44, size.y - 38), Color("#183344"), Color("#325665"))

func paint_words(words: String, at: Vector2, pixels: int = 16, ink: Color = PAPER) -> void:
	draw_string(ThemeDB.fallback_font, at, words, HORIZONTAL_ALIGNMENT_LEFT, -1, pixels, ink)

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 ControlStarts with Godot's Control type. This script gets the abilities of that type and adds the game's own rules.
  2. const COLS := 4Four x coordinates run from zero to three.
  3. const ROWS := 3Three y coordinates run from zero to two.
  4. var current := Vector2i.ZEROCreates a variable named current. The expression reads Vector2i.ZERO. Godot infers the type from the first value.
  5. var cells: Array[Button] = []Creates a variable named cells. The expression makes a list whose items keep their order. The type after the colon says what kind of value it can hold.
  6. var info: LabelDeclares info for later use. A colon followed by a type says which kind of value belongs here.
  7. var headline: LabelDeclares headline for later use. A colon followed by a type says which kind of value belongs here.
  8. func _ready() -> void:Godot calls this once after the scene and its children are ready. Use it to set up the room and connect controls.
  9. headline = label("Touch and keys", Vector2(44, 62), 33)Stores the new value in headline. The expression calls label with the values in its parentheses.
  10. label("TINY SHELF STUDIO / TOUCH", Vector2(44, 35), 14, GOLD)Calls label with the values in its parentheses.
  11. info = label("", Vector2(44, 113), 16, SEA)Stores the new value in info. The expression calls label with the values in its parentheses.
  12. for y in range(ROWS):Repeats the indented instructions for each value in range(ROWS).
  13. for x in range(COLS):Repeats the indented instructions for each value in range(COLS).
  14. var control := place_button("", Vector2.ZERO, choose.bind(Vector2i(x, y)), 48)Tie each button to a point by binding the current loop's column and row.
  15. control.focus_mode = Control.FOCUS_NONEKeep the keyboard arrows free to move the shelf selection in this checkpoint. The active grid cell is highlighted with its own state.
  16. cells.append(control)Adds an item to the end of a list.
  17. resized.connect(layout)When Godot reports a changed Control size, recalculate each button's position.
  18. layout()Calls layout with the values in its parentheses.
  19. choose(Vector2i.ZERO)Calls choose with the values in its parentheses.
  20. func layout() -> void:Defines layout, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  21. var narrow := size.x < 550.0Change visual spacing below 550 logical pixels. The selection rules remain the same.
  22. var spacing := Vector2(57.0, 67.0) if narrow else Vector2(144.0, 85.0)Creates a variable named spacing. The expression packs x and y into one value. Godot infers the type from the first value.
  23. var start := Vector2(44.0, 167.0)Creates a variable named start. The expression packs x and y into one value. Godot infers the type from the first value.
  24. for i in range(cells.size()):Repeats the indented instructions for each value in range(cells.size()).
  25. var x := i % COLSUse the remainder after division by four as the column number.
  26. var y := int(floor(float(i) / COLS))Count completed four-cell rows to get the zero-based row number.
  27. cells[i].size = spacing - Vector2(8.0, 8.0)Leave a visible gap around each target. The button requests a minimum size of 48 by 48.
  28. cells[i].position = start + Vector2(x, y) * spacingUpdates cells[i].position, which controls the node's local x and y location. The expression calculates a new value from the expressions on either side of the operator.
  29. queue_redraw()Asks Godot to call _draw again on a later frame so the screen matches the new state.
  30. func choose(point: Vector2i) -> void:Defines choose, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  31. current = Vector2i(clampi(point.x, 0, COLS - 1), clampi(point.y, 0, ROWS - 1))Keep both coordinates within limits before using them to compute the active index.
  32. var active := current.y * COLS + current.xSkip four cells for every full row before adding the column number.
  33. for i in range(cells.size()):Repeats the indented instructions for each value in range(cells.size()).
  34. cells[i].text = "✓" if i == active else str(i + 1)Updates cells[i].text, which controls the words a player sees. The expression chooses one of two values by checking the condition in the middle.
  35. info.text = "Selected row %d, column %d" % [current.y + 1, current.x + 1]Updates info.text, which controls the words a player sees. The expression uses the text inside the quotes.
  36. func _unhandled_key_input(event: InputEvent) -> void:Defines unhandled key input, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  37. if not event is InputEventKey or not event.pressed or event.echo:Ignore releases, non-key events and automatic repeats.
  38. returnFinishes the function right here. Any later instructions in this function are skipped.
  39. match event.keycode:Compares event.keycode to the patterns below and runs the first matching branch.
  40. KEY_UP:Starts the instructions for this branch. The indented lines belong together.
  41. choose(current + Vector2i.UP)Calls choose with the values in its parentheses.
  42. KEY_RIGHT:Starts the instructions for this branch. The indented lines belong together.
  43. choose(current + Vector2i.RIGHT)Calls choose with the values in its parentheses.
  44. KEY_DOWN:Starts the instructions for this branch. The indented lines belong together.
  45. choose(current + Vector2i.DOWN)Calls choose with the values in its parentheses.
  46. KEY_LEFT:Starts the instructions for this branch. The indented lines belong together.
  47. choose(current + Vector2i.LEFT)Calls choose with the values in its parentheses.
  48. _:Handles every match value that the branches above did not handle.
  49. returnFinishes the function right here. Any later instructions in this function are skipped.
  50. get_viewport().set_input_as_handled()After a known key changes the shelf selection, tell Godot there is no remaining handler work to do.
  51. func _draw() -> void:Godot calls this when the node needs drawing. The instructions inside paint the current state.
  52. backdrop()Calls backdrop with the values in its parentheses.
  53. const PAPER := Color("#fff4de")Creates a constant named PAPER. The expression builds a colour from these values. Godot infers the type from the first value.
  54. const GOLD := Color("#f5bd79")Creates a constant named GOLD. The expression builds a colour from these values. Godot infers the type from the first value.
  55. const SEA := Color("#9ddcd0")Creates a constant named SEA. The expression builds a colour from these values. Godot infers the type from the first value.
  56. const INK := Color("#172c3c")Creates a constant named INK. The expression builds a colour from these values. Godot infers the type from the first value.
  57. const EDGE := Color("#54817f")Creates a constant named EDGE. The expression builds a colour from these values. Godot infers the type from the first value.
  58. func title_page(unit: String, heading: String, subtitle: String) -> void:Defines title page, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  59. label("TINY SHELF STUDIO / " + unit, Vector2(44, 36), 14, GOLD)Make a small line above the main heading so you can tell which checkpoint is open.
  60. label(heading, Vector2(44, 65), 33)Calls label with the values in its parentheses.
  61. label(subtitle, Vector2(46, 119), 16, SEA)Calls label with the values in its parentheses.
  62. func label(words: String, at: Vector2, pixels: int = 20, ink: Color = PAPER) -> Label:Defines label, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  63. var item := Label.new()Creates a variable named item. The expression creates a new Label object. Godot infers the type from the first value.
  64. item.text = wordsUpdates item.text, which controls the words a player sees. The expression reads words.
  65. item.position = atUpdates item.position, which controls the node's local x and y location. The expression reads at.
  66. item.add_theme_font_size_override("font_size", pixels)This Label has its own readable type size. Changing that value leaves the other labels alone.
  67. item.add_theme_color_override("font_color", ink)This label keeps the chosen text ink even when the default theme changes.
  68. add_child(item)Adds the new node to the scene tree so that Godot can run and draw it.
  69. return itemFinishes the function and hands its result back to the caller. The expression reads item.
  70. func place_button(words: String, at: Vector2, action: Callable, width: float = 170.0) -> Button:Defines place button, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  71. var control := Button.new()Creates a variable named control. The expression creates a new Button object. Godot infers the type from the first value.
  72. control.text = wordsUpdates control.text, which controls the words a player sees. The expression reads words.
  73. control.position = atUpdates control.position, which controls the node's local x and y location. The expression reads at.
  74. control.custom_minimum_size = Vector2(width, 48)Give the button room for its label and an easy target for taps. Containers and layouts can allocate more space.
  75. control.add_theme_font_size_override("font_size", 17)Calls control.add_theme_font_size_override with the values in its parentheses.
  76. control.add_theme_color_override("font_color", PAPER)Calls control.add_theme_color_override with the values in its parentheses.
  77. control.add_theme_stylebox_override("normal", style(Color("#244557"), EDGE))Calls control.add_theme_stylebox_override with the values in its parentheses.
  78. control.add_theme_stylebox_override("hover", style(Color("#365a62"), SEA))Calls control.add_theme_stylebox_override with the values in its parentheses.
  79. control.add_theme_stylebox_override("pressed", style(Color("#315b56"), SEA))Calls control.add_theme_stylebox_override with the values in its parentheses.
  80. control.add_theme_stylebox_override("focus", style(Color.TRANSPARENT, GOLD, 3))Draw a gold outline around keyboard focus. Other button styles can still indicate hover and press independently.
  81. control.pressed.connect(action)pressed fires on a successful control activation. Godot calls the function passed in without running it at setup time.
  82. add_child(control)Adds the new node to the scene tree so that Godot can run and draw it.
  83. return controlFinishes the function and hands its result back to the caller. The expression reads control.
  84. func style(fill: Color, edge: Color, line: int = 1) -> StyleBoxFlat:Defines style, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  85. var block := StyleBoxFlat.new()Creates a variable named block. The expression creates a new StyleBoxFlat object. Godot infers the type from the first value.
  86. block.bg_color = fillStores the new value in block.bg_color. The expression reads fill.
  87. block.border_color = edgeStores the new value in block.border_color. The expression reads edge.
  88. block.set_border_width_all(line)Apply one border line width to all four edges of the card.
  89. block.set_corner_radius_all(8)Round each corner of this reusable style by eight pixels.
  90. return blockFinishes the function and hands its result back to the caller. The expression reads block.
  91. func panel(rect: Rect2, fill: Color, edge: Color = EDGE) -> void:Defines panel, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  92. draw_style_box(style(fill, edge), rect)Calls draw_style_box with the values in its parentheses.
  93. func backdrop() -> void:Defines backdrop, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  94. draw_rect(Rect2(Vector2.ZERO, size), Color("#102333"))Paints a rectangle at the given position and size.
  95. panel(Rect2(22, 19, size.x - 44, size.y - 38), Color("#183344"), Color("#325665"))Subtract space on both sides of the canvas. As the window changes, the outer frame fits within it.
  96. func paint_words(words: String, at: Vector2, pixels: int = 16, ink: Color = PAPER) -> void:Defines paint words, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  97. draw_string(ThemeDB.fallback_font, at, words, HORIZONTAL_ALIGNMENT_LEFT, -1, pixels, ink)Godot draws the words from the baseline at the supplied pixel position using its fallback typeface.

Find and fix a bug

If a long title is clipped in a narrow design, shorten it or let the Label wrap within a width. Keep the grid controls comfortably tappable.

Try a change

Add a Home key shortcut for the first slot. The change should use choose and reuse its guard.