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 = trueBoom 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
Medium- In
rock.gd, addsignal hit_shipand emit it when the body is theShip. - In
main.gd, connect it inspawn_rockto_on_hit_ship. It showsGame Over, hides the ship, bursts$Boomwhere the ship was and pauses the game. - 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
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Projects
2Project: Asteroid Shooter
Turn the ShipFire the EnginePractice on your own: Godot playground