Breakout Score
Part of the Projects section of Coddy's Godot journey. Lesson 7 of 33.
Every brick is worth 10 points. The ball knows when it breaks one, and main.gd keeps the score. A signal connects them. The ball emits it for each broken brick, and the main script listens.
In ball.gd, declare the signal at the top and emit it next to smash():
signal brick_broken
# in _on_body_entered, after body.smash():
brick_broken.emit()In main.gd, connect it in _ready and add the points in the function it calls:
func _on_brick_broken():
score += 10
$HUD/Score.text = "Score: %d" % scoreThe label is in a CanvasLayer called HUD. Set it to Score: 0 in _ready too, or it stays empty until the first brick.
Challenge
Medium- In
ball.gd, addsignal brick_brokenand emit it when a brick breaks. - In
main.gd, addvar score = 0, connect$Ball.brick_brokento a function that adds 10 and showsScore: 10,Score: 20, ... in$HUD/Score. - Show
Score: 0when the game starts.
Try it yourself
extends Node2D
const BRICK = preload("res://brick.tscn")
const COLORS = [Color(1, 0.42, 0.42), Color(1, 0.78, 0.34), Color(0.49, 0.95, 0.75), Color(0.369, 0.635, 1), Color(0.75, 0.82, 0.95)]
func _ready():
for row in 5:
for column in 8:
var brick = BRICK.instantiate()
brick.position = Vector2(68 + column * 72, 60 + row * 26)
brick.color = COLORS[row]
add_child(brick)
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