Change Ball direction in Breakout game

Godot Version




I’m working on a simple Breakout game just as a way to learn the engine and GDScript.

I’m trying to figure out how to detect what part of the paddle the ball hit and change it’s deflection angle based on that. Right now, now matter what part it hits it always follows the same angle.

Is it possible to say for example it can be a range of 0-180 based on what part of the paddle it hits?

This is my entire Paddle and Ball code

extends CharacterBody2D
class_name Paddle

var speed : float =  500.0
var deceleration : float  = 450

@onready var ball = $Ball
@onready var marker_2d = $Marker2D

var is_launched : bool = false

func _physics_process(delta):
	var direction = Input.get_axis("Left", "Right")
	if direction:
		velocity.x = direction * speed
		if velocity.x > 0:
			velocity.x = max(velocity.x - deceleration * delta, 0)
		elif velocity.x < 0:
			velocity.x = min(velocity.x + deceleration * delta, 0)
	velocity.y = 0

func serve():
	if is_launched: return
	is_launched = true
	ball.top_level = true
	ball.global_position = marker_2d.global_position
	ball.global_rotation_degrees = -90 + 13 
	ball.set_velocity(Vector2.UP * ball.ball_speed)
func _input(event):
	if event.is_action_pressed("Start"):
extends CharacterBody2D
class_name Ball

var ball_speed : float = 1000.0

func _ready():

func _physics_process(delta):
	var movement = Vector2.RIGHT.rotated(self.rotation) * ball_speed * delta
	var collision = move_and_collide(movement)
	if collision:
		self.rotation = Vector2.from_angle(self.rotation).bounce(collision.get_normal()).angle()

func _on_area_2d_body_entered(body):
	if body.is_in_group("Block"):

you can compute the distance in the x axis between the ball and the paddle and use it to modify the rotation of the ball.

var collider = collision.get_collider()
if collider is Paddle:
	var dist = global_position.x - collider.global_position.x 
1 Like