Menu
CoddyTech

Break the Bricks

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

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

In _on_body_entered, add an elif for bodies in the group bricks:

  1. Call body.smash().
  2. Bounce the ball down if it is below the brick's middle, up if it is above.

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)
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