Bounce Off the Paddle
Part of the Projects section of Coddy's Godot journey. Lesson 4 of 33.
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
MediumIn ball.gd, make the ball bounce off the paddle:
- Connect
body_enteredto_on_body_enteredin_ready. - When the body's name is
Paddle, setvelocity.xto(position.x - body.position.x) * 5andvelocity.yto-abs(velocity.y).
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
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Projects
1Project: Breakout
Breakout PaddleKeep the Paddle on ScreenPractice on your own: Godot playground