Menu
CoddyTech

Crash and Restart

Part of the Projects section of Coddy's Godot journey. Lesson 18 of 33.

The ship flies through rocks. A rock that touches the ship should end the game. In rock.gd's _on_body_entered, the ship is the body named Ship. The rock emits a hit_ship signal. main.gd connects it in spawn_rock and ends the game:

func _on_hit_ship():
	$HUD/Message.text = "Game Over"
	$Ship.hide()
	$Boom.position = $Ship.position
	$Boom.emitting = true
	get_tree().paused = true

Boom is a one-shot CPUParticles2D. Set emitting to true and it bursts once. It is a child of Main, which is Always, so it plays while the game is paused.

Last, let Enter start a new game while paused, as in Breakout: unpause, then reload_current_scene(). It works after a win too.

challenge icon

Challenge

Medium
  1. In rock.gd, add signal hit_ship and emit it when the body is the Ship.
  2. In main.gd, connect it in spawn_rock to _on_hit_ship. It shows Game Over, hides the ship, bursts $Boom where the ship was and pauses the game.
  3. While paused, Enter unpauses and reloads the scene.

Try it yourself

extends Node2D

const ROCK = preload("res://rock.tscn")

var score = 0
var rocks_left = 4

func _ready():
	for i in 4:
		spawn_rock(Vector2(randf_range(0, 640), 0), Vector2(randf_range(-90, 90), randf_range(40, 90)), 2)
	$HUD/Score.text = "Score: 0"

func spawn_rock(where, velocity, size):
	var rock = ROCK.instantiate()
	rock.position = where
	rock.velocity = velocity
	rock.size = size
	rock.broken.connect(_on_rock_broken)
	add_child(rock)

func _on_rock_broken(rock):
	if rock.size == 2:
		spawn_rock.call_deferred(rock.position, rock.velocity.rotated(0.8) * 1.5, 1)
		spawn_rock.call_deferred(rock.position, rock.velocity.rotated(-0.8) * 1.5, 1)
		score += 20
		rocks_left += 2
	else:
		score += 50
	rocks_left -= 1
	$HUD/Score.text = "Score: %d" % score
	if rocks_left == 0:
		$HUD/Message.text = "You Win!"
		get_tree().paused = true
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Projects

Practice on your own: Godot playground