Mobile Game 33 · Make touch and keyboard share one control

Museum of Lost Lights · Lesson 33 of 50 · Intermediate to advanced · About 36 min

A player can solve your gallery on a phone or at a desk. Give both players a way to turn the mirror and undo their last move.

A gouache painting of a Space Gallery with celestial exhibits, a midnight-blue floor and a domed ceiling.
What you’ll make Build larger buttons and route tapping, clicking and keyboard activation through the same mirror instruction.

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

Activate Button. Tap, click or use keyboard focus. → Call turn rule. Each callback sends either -1 or +1. → Remember prior angle. Append before changing the angle. → Show new angle. Wrap around a circle and redraw arrow and words.
Activate Button → Call turn rule → Remember prior angle → Show new angle

Build it step by step

Language and tools in this lesson Button.pressed, Vector2, Callable, lambda, posmod, grab_focus, Array.pop_back.

  1. Open the controls lab

    Import the project.godot for lesson 33 and press F5. Click both direction buttons with a mouse, then press Tab and Space to do the same using keyboard focus.

    Why it works Built-in Button controls support different ways to act. Connecting pressed joins those inputs to the same game rule.

  2. Give fingers enough room

    Open main.gd. In make_button, find the line that sets the minimum button height. Change 52 to 64, run and compare the three buttons.

    button.custom_minimum_size.y = 52

    Why it works custom_minimum_size.y sets a lower limit vertically. In a layout container, it lets the control ask for enough room for a comfortable target.

  3. Pass a turn direction

    Return to _ready. Compare the two lines containing func(). Mark the -1 from Turn left and the 1 from Turn right.

    func(): rotate_mirror(-1)

    Why it works func() without a name makes a short callable. The button waits until pressed before running the callable with its direction value.

  4. Wrap the angle

    Try pressing Turn left at 0°. Follow the line that adds -90. Then compare the output angle to the negative number you calculated on paper.

    angle = posmod(angle + direction * 90, 360)

    Why it works posmod returns a wrapped position. When turns use a 360-degree circle, the result maps -90 to 270 and maps 360 back to 0.

  5. Save and undo a turn

    Look at append before the angle calculation and pop_back in undo_turn. Press Undo first, then turn twice and undo twice.

    angle = previous_angles.pop_back()

    Why it works append records the old angle. pop_back takes out the latest saved angle. The early return prevents Godot from trying to take an item from an empty array.

  6. Choose where keyboard focus starts

    Find left.grab_focus(). Run again and press Space before clicking a button. Check which action happens.

    Why it works grab_focus gives attention to the first action. A player can begin immediately with a keyboard.

Watch the values change

  1. Start angle = 0 and history is empty.
    What you see. Readout shows ↑ Mirror angle 0 degrees.
  2. Turn left History becomes [0]. posmod(-90, 360) gives 270.
    What you see. Readout points left at 270 degrees.
  3. Undo pop_back returns 0. History becomes empty.
    What you see. Readout points up at 0 degrees.

Predict before you run Start at 0°. Turn right twice and then Undo. What should the angle and arrow show?

Reveal the answer

The turns take you to 90° and then 180°. Undo restores 90°, so the arrow points right.

Complete checkpoint

Both click and keyboard activation produce the same rotation. Turns wrap from 0 to 270 or 270 to 0, and undo returns to the exact prior angle.

main.gd

extends Control

var angle := 0
var previous_angles: Array[int] = []
var angle_readout: Label

func _ready() -> void:
	var panel := make_panel("33 · Make touch and keyboard share one control")
	make_label(panel, "Tap a button, or press Tab and then Space.")
	angle_readout = make_label(panel, "", 26)
	var left := make_button(panel, "Turn left 90°", func(): rotate_mirror(-1))
	make_button(panel, "Turn right 90°", func(): rotate_mirror(1))
	make_button(panel, "Undo last turn", undo_turn)
	left.grab_focus()
	show_angle()

func rotate_mirror(direction: int) -> void:
	previous_angles.append(angle)
	angle = posmod(angle + direction * 90, 360)
	show_angle()

func undo_turn() -> void:
	if previous_angles.is_empty():
		return
	angle = previous_angles.pop_back()
	show_angle()

func show_angle() -> void:
	var icon: String = ["↑", "→", "↓", "←"][int(angle / 90.0)]
	angle_readout.text = "%s  Mirror angle %d degrees" % [icon, angle]

func make_panel(heading: String, width: float = 580.0) -> VBoxContainer:
	var margin := MarginContainer.new()
	margin.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)
	for side in ["left", "right", "top", "bottom"]:
		margin.add_theme_constant_override("margin_" + side, 24)
	add_child(margin)
	var centring := CenterContainer.new()
	margin.add_child(centring)
	var panel := VBoxContainer.new()
	panel.custom_minimum_size.x = width
	panel.add_theme_constant_override("separation", 12)
	centring.add_child(panel)
	make_label(panel, heading, 28)
	return panel

func make_label(parent: Control, message: String, size: int = 18) -> Label:
	var label := Label.new()
	label.text = message
	label.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
	label.add_theme_font_size_override("font_size", size)
	parent.add_child(label)
	return label

func make_button(parent: Control, caption: String, handle_press: Callable) -> Button:
	var button := Button.new()
	button.text = caption
	button.custom_minimum_size.y = 52
	button.pressed.connect(handle_press)
	parent.add_child(button)
	return button

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 ControlGive this script the layout and input abilities of Godot's Control node. The code below turns the root Control into a particular museum practice scene.
  2. var angle := 0Creates a variable named angle. The expression uses the whole number 0. Godot infers the type from the first value.
  3. var previous_angles: Array[int] = []Start an empty list that can store only whole-number angles. Each accepted move will add its previous angle to this list.
  4. var angle_readout: LabelDeclares angle_readout for later use. A colon followed by a type says which kind of value belongs here.
  5. func _ready() -> void:Godot calls this function once when the node is ready. The indented setup creates the interface and gives its controls their starting values.
  6. var panel := make_panel("33 · Make touch and keyboard share one control")Creates a variable named panel. The expression calls make_panel with the values in its parentheses. Godot infers the type from the first value.
  7. make_label(panel, "Tap a button, or press Tab and then Space.")Calls make_label with the values in its parentheses.
  8. angle_readout = make_label(panel, "", 26)Stores the new value in angle_readout. The expression calls make_label with the values in its parentheses.
  9. var left := make_button(panel, "Turn left 90°", func(): rotate_mirror(-1))Make a left-turn button, keep it in left, and give a short unnamed callback the direction -1 for later.
  10. make_button(panel, "Turn right 90°", func(): rotate_mirror(1))Give the right-turn button a callback that passes 1 to the shared rotate function.
  11. make_button(panel, "Undo last turn", undo_turn)Calls make_button with the values in its parentheses.
  12. left.grab_focus()Choose the left button as the starting keyboard target so the player can begin by pressing Space.
  13. show_angle()Calls show_angle with the values in its parentheses.
  14. func rotate_mirror(direction: int) -> void:Defines rotate mirror, 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.
  15. previous_angles.append(angle)Remember the current angle before changing it, since that's the value Undo will need.
  16. angle = posmod(angle + direction * 90, 360)Add one signed quarter-turn, then wrap the result into the range from 0 up to 359. A negative quarter-turn from zero becomes 270.
  17. show_angle()Calls show_angle with the values in its parentheses.
  18. func undo_turn() -> void:Defines undo turn, 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.
  19. if previous_angles.is_empty():Check whether there is no earlier angle to restore. The early return in the next line leaves the mirror where it is.
  20. returnFinishes the function right here. Any later instructions in this function are skipped.
  21. angle = previous_angles.pop_back()Remove the most recently stored angle from the list and make that the current angle.
  22. show_angle()Calls show_angle with the values in its parentheses.
  23. func show_angle() -> void:Defines show angle, 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.
  24. var icon: String = ["↑", "→", "↓", "←"][int(angle / 90.0)]Divide by 90 and convert to a whole number to make an index from 0 to 3. Use that position to choose a direction arrow.
  25. angle_readout.text = "%s Mirror angle %d degrees" % [icon, angle]Display both the directional icon and the whole-number angle, using placeholder order.
  26. func make_panel(heading: String, width: float = 580.0) -> VBoxContainer:Make a helper that takes the heading text and the panel's minimum width. If the caller omits the width, use 580 game pixels. Return the laid-out panel so the caller can add more controls.
  27. var margin := MarginContainer.new()Create a container that can reserve clear space between the game controls and the window edges.
  28. margin.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)Choose the preset that aligns the margin's edges with all four edges of the parent Control.
  29. for side in ["left", "right", "top", "bottom"]:Visit the four names in order so the following indented line can set one margin on each trip through the loop.
  30. margin.add_theme_constant_override("margin_" + side, 24)Join margin_ to the current side's name. Set that edge to 24 game pixels, and repeat for the other sides.
  31. add_child(margin)Connect the completed margin container to the lesson's scene root so it can lay out its children.
  32. var centring := CenterContainer.new()Make a container that will centre the controls within the available space.
  33. margin.add_child(centring)Give the centring container the space inside the extra border, then let it place the panel within that space.
  34. var panel := VBoxContainer.new()Create a container that arranges its child controls in one vertical column.
  35. panel.custom_minimum_size.x = widthAsk the layout for at least the selected width, where x is the horizontal part of the size.
  36. panel.add_theme_constant_override("separation", 12)Leave 12 game pixels of space between each pair of controls in the vertical panel.
  37. centring.add_child(panel)Attach the vertical column to the centring container. Godot can now place the whole column together.
  38. make_label(panel, heading, 28)Put the supplied heading at the top of the column and ask for a larger 28-pixel font.
  39. return panelHand the panel reference back to the caller so it can add labels or buttons under the heading.
  40. func make_label(parent: Control, message: String, size: int = 18) -> Label:Accept the parent control, text to show and optional font size. Return the new Label so the caller can update it later.
  41. var label := Label.new()Make a new empty Label, which is Godot's text display node.
  42. label.text = messageCopy the incoming message into the label's visible words.
  43. label.autowrap_mode = TextServer.AUTOWRAP_WORD_SMARTLet the label wrap lines at sensible places so a long message can fit when the layout is narrow.
  44. label.add_theme_font_size_override("font_size", size)Set the chosen size on this one label so other text can keep different sizes.
  45. parent.add_child(label)Add the label to the supplied parent. It becomes part of that panel's layout and can appear on screen.
  46. return labelReturn the exact label you created so the caller can change its text without building a second label.
  47. func make_button(parent: Control, caption: String, handle_press: Callable) -> Button:Build and return one Button. The arguments identify its parent, the words on it and the action to run after pressing it.
  48. var button := Button.new()Create a Godot Button that supports pointer, touch and keyboard activation.
  49. button.text = captionPut the supplied caption on the visible control.
  50. button.custom_minimum_size.y = 52Reserve at least 52 game pixels vertically so the control remains a comfortable target.
  51. button.pressed.connect(handle_press)Connect the pressed signal to the supplied callable. Godot waits for activation before running the action.
  52. parent.add_child(button)Attach the Button to its parent and let that container position it.
  53. return buttonGive the finished Button to the caller, which can keep a reference to set focus or change the caption later.

Find and fix a bug

If the first turn left shows a negative angle, check your wrap operation. posmod(-90, 360) should give 270.

Try a change

Ages 10–12 can add a Reset button that clears the array and returns to zero. Ages 13–16 can add redo and test that making a new turn after undo clears the redo history.