Using velocity.bounce(Vector2(0,1)) sometimes makes it bounce strangely

Godot Version

4.3

Question

My code:

func _physics_process(delta: float) -> void:
	var collision = move_and_collide(velocity * delta)
	if collision:
		velocity = velocity.bounce(collision.get_normal())
	
	var ball_loc = get_position()
	
	if ball_loc.x < 0:
		lost.emit()
	if ball_loc.x > screen_size_mp.x:
		won.emit()
	if ball_loc.y < 0:
		velocity = velocity.bounce(Vector2(0,1))
	if ball_loc.y > screen_size_mp.y:
		velocity = velocity.bounce(Vector2(0,-1))

Full code here

I’m building a simple pong game and the last 4 lines are the problem - the ball bounces off the top and bottom of the screen just fine 99% of the time, however that 1% of the time it’ll get caught or something and just bounce a few pixels up and down while moving horizontally.

I’d also like to add some of the velocity from the paddle’s movement on bounce and figure out how to clamp the speed so it’s always going at least half the max speed in velocity.x but have no idea what to even search for to figure that out.

Any help would be appreciated.

I’d guess that the ball moved fast enough to be outside the bounds, but the next frame did not move fast enough to be bounced back into the bounds. Thus continously bouncing just barely outside the bounds

It could be a good check to ensure the ball is moving towards the top and bottom wall too

if ball_loc.y < 0 and velocity.y < 0:
	velocity = velocity.bounce(Vector2(0,1))
if ball_loc.y > screen_size_mp.y and velocity.y > 0:
	velocity = velocity.bounce(Vector2(0,-1))
1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.