How does the bounce() function work?

Godot Version

v 4.6.1

Question

After trying to make a bouncing ball, I discovered this function, but I don`t understand very well how it works. Could someone please explain in details what happens in the _physics_process() function?

Code:

extends CharacterBody2D

var speed: int = 450
var direction: Vector2

func _ready():
	#Defines the direction of the ball
	var x = [1, -1].pick_random()
	var y = [1, -1].pick_random()
	direction = Vector2(x, y)
	
	velocity = direction * speed

#Controls bouncing
func _physics_process(delta):
	var collision = move_and_collide(direction * speed * delta)
	if collision:
		direction = direction.bounce(collision.get_normal())

Here’s documentation explaining what this function does:

You checked for collision and then assigned a bounced vector off the collision’s normal to a direction variable.

You haven’t explained what you’re trying to do vs what’s happening, so we can’t say if the code works correctly and how to fix it.

1 Like

The code was meant to control the ball for ping pong, and thanks for helping!