Breakout Score
Part of the Projects section of Coddy's Godot journey. Lesson 7 of 36.
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
MediumScore 10 points for each brick.
- In
ball.gd, addsignal brick_brokenand emit it when a brick breaks. - In
main.gd, addvar score = 0and showScore: 0in$HUD/Scorein_ready. - Connect
$Ball.brick_brokento a function that adds 10 and shows the score.
Press Play and break a brick: the label shows Score: 10. Then Check.
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)
All lessons in Projects
Practice on your own: Godot playground