A physics body freezes when moved by another one

Godot Version

v 4.6.1

Question

After making a working ball and player for a ping pong clone, everything seemed normal at first. But when the ball collides with the side of the player (not on top of it), it completelly freezes when the player moves, but when the player stops, the ball acts normal again.

Code

The Player:

extends CharacterBody2D

var speed: int = 300
var direction: Vector2

func _ready():
	global_position = Vector2(960, 1000)

func _process(_delta):
	if Input.is_action_pressed("left"):
		direction.x = -1
	elif Input.is_action_pressed("right"):
		direction.x = 1
	else:
		direction.x = 0
	velocity = direction * speed
	move_and_slide()

The Ball:

extends CharacterBody2D

var direction = Vector2.ZERO
var speed = 450

func _ready():
	global_position = Vector2(960, 700)
	#Each variable gets a random number for direction
	direction.x = [1, -1].pick_random()
	direction.y = [1, -1].pick_random()
	print(direction)
	velocity = speed * direction

#Controls the movement of the ball
func _physics_process(delta):
	var collision = move_and_collide(direction * speed * delta)
	if collision:
		direction = direction.bounce(collision.get_normal())

Is it possible that the ball is bouncing in the same direction the player paddle is moving, which causes it collide again on the next frame?

1 Like

Yes, its exactly how the problem occurs

You could check if the ball is moving towards the wall it hit before using bounce

1 Like

Don’t know who to ask so I’m just going to reply to the whole comment.
Is therev and advantage to using

 [ -1 , 1 ].pick_random()

Versus

randi_range(-1, 1)

randi_range includes 0, where [-1, 1].pick_random() will never pick 0

2 Likes