Godot Version
v4.3.stable
Question
I am trying to recreate breakout but I encountered a problem, I want the ball to bounce to the left if it hits the left of the paddle, and the same for the right, but the closest I was able to get to working was the code bellow but it doesn’t matter where it hits the player(or the paddle) it only bounces to the left, I tried playing with global position and just position and this was the only one that was close to working.
func _on_area_2d_body_entered(body: Node2D) -> void:
if body.name.contains("BallBody"):
var body_position = body.position
print("body global: " + str(body_position))
print("body pos: " + str(body.position))
print("player global: " + str($Area2D.global_position))
print("player pos: " + str($Area2D.position))
var ball_dir = $Area2D.global_position.direction_to(body_position)
print(ball_dir)
ball_dir.y /= 2
GlobalVariables.velocity = ball_dir * GlobalVariables.ball_vel
Here are the printed positions when the ball enters the area2d:
body global: (70.07361, 10.86853)
body pos: (70.07361, 10.86853)
player global: (576, 600)
player pos: (0, 0)
(-0.651501, -0.758648)
here is the global variables:
var ball_vel = 500
var randomize_x_direction = randf_range(-0.5, 0.5)
var velocity = Vector2(randomize_x_direction, -1) * ball_vel
and here is the ball code:
const ball_size: float = 7.0
func _ready() -> void:
#information so the ball keeps stuck to the player trough the "magnet"
set_ball_stop()
func _process(delta: float) -> void:
if Input.is_action_just_pressed("start_ball"):
set_ball_moving()
if GlobalVariables.is_ball_moving == true:
var collision = $BallBody.move_and_collide(GlobalVariables.velocity * delta)
if collision:
GlobalVariables.velocity = GlobalVariables.velocity.bounce(collision.get_normal())
queue_redraw()
func _draw() -> void:
var ball_pos = $BallBody.position
#Draws the ball
draw_circle(ball_pos, ball_size, Color.WHITE, true, -1.0, true)
func set_ball_moving():
GlobalVariables.is_ball_moving = true
func set_ball_stop():
GlobalVariables.is_ball_moving = false