Menu
CoddyTech

Bounce Off the Paddle

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

The ball passes through the paddle. The ball is an Area2D. Its body_entered signal fires when a body, like the paddle, touches it. Turn the ball up when that body is the paddle:

func _ready():
	body_entered.connect(_on_body_entered)

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

abs() drops the minus sign, so -abs(velocity.y) always points up. A second touch cannot send the ball back down.

To let the player aim, set velocity.x from where the ball hits. position.x - body.position.x is the ball's distance from the paddle's middle. It is negative on the left half and positive on the right. Multiply it by 5.

challenge icon

Challenge

Medium

Make the ball bounce off the paddle.

  1. In ball.gd, connect body_entered to _on_body_entered in _ready.
  2. When the body's name is Paddle, set velocity.x to (position.x - body.position.x) * 5 and velocity.y to -abs(velocity.y).

Press Play and catch the ball: it flies back up, toward the side it hit. Then Check.

Try it yourself

extends Area2D

var velocity = Vector2(110, -280)

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

All lessons in Projects

Practice on your own: Godot playground