Menu
CoddyTech

Break the Bricks

Part of the Projects section of Coddy's Godot journey. Lesson 6 of 36.

The ball passes through the bricks. Bricks are bodies too, and each one is in the group bricks. is_in_group tells a brick from the paddle.

Each brick has a smash() function. It bursts the brick into sparks and removes it.

elif body.is_in_group("bricks"):
	body.smash()

Then the ball bounces away from the brick's middle: down if it is lower than the brick, up if it is higher. A ball can hit a brick from above after slipping through a gap.

if position.y > body.position.y:
	velocity.y = abs(velocity.y)
else:
	velocity.y = -abs(velocity.y)

Do not flip velocity.y. If the ball touches two bricks at once, two flips cancel out.

challenge icon

Challenge

Medium

Let the ball break bricks.

  1. In _on_body_entered, add an elif for bodies in the group bricks.
  2. Call body.smash().
  3. Bounce the ball down if it is below the brick's middle, up if it is above.

Press Play: bricks burst one at a time. Then Check.

Try it yourself

extends Area2D

var velocity = Vector2(110, -280)

func _ready():
	body_entered.connect(_on_body_entered)

func _physics_process(delta):
	position += velocity * delta
	if position.x < 8 or position.x > 632:
		velocity.x = -velocity.x
	if position.y < 42:
		velocity.y = -velocity.y

func _on_body_entered(body):
	if body.name == "Paddle":
		velocity.x = (position.x - body.position.x) * 5
		velocity.y = -abs(velocity.y)

All lessons in Projects

Practice on your own: Godot playground