Restart on a Key
Part of the Game Rules section of Coddy's Godot journey. Lesson 15 of 29.
This line throws the scene away and loads it fresh from its file:
get_tree().reload_current_scene()The new game starts with three lives, the player on the green square and Game Over hidden.
Main is paused too, so its _process never sees the key. Set Main's own process_mode to Node.PROCESS_MODE_ALWAYS. Its children inherit that, except the player. The scene sets the player to Pausable, so it still stops.
Reloading does not unpause the game. Set get_tree().paused = false before you reload, or the new game starts paused.
Challenge
EasyLet the player press E to play again after Game Over:
- In
_ready(), set this node'sprocess_modetoNode.PROCESS_MODE_ALWAYS. - In
_process(), whenlivesis 0 andactionwas just pressed, unpause the game and reload the scene.
Try it yourself
extends Node2D
var lives = 3
func _ready():
$HUD/Lives.text = "Lives: %d" % lives
$Player.hurt.connect(_on_player_hurt)
$Blink.timeout.connect(_on_blink_timeout)
$Blink.process_mode = Node.PROCESS_MODE_ALWAYS
func _process(delta):
pass
func _on_player_hurt():
lives -= 1
$HUD/Lives.text = "Lives: %d" % lives
if lives == 0:
$HUD/GameOver.visible = true
$HUD/Hint.visible = true
get_tree().paused = true
func _on_blink_timeout():
if lives == 0:
$HUD/GameOver.visible = not $HUD/GameOver.visible
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Game Rules
Practice on your own: Godot playground