My ball starts freaking out on collision (2D Pong-like game)

Godot Version

4.3

Question

Hello! I am an aspiring Godot game developer making a pong-like game as a small project, while I study GDScript and the engine. However, I’ve faced a problem, which is driving me crazy. My ball (CharacterBody2D) doesn’t bounce on collision. Instead, it starts jittering. Here’s the code btw:

extends CharacterBody2D

func LaunchBall(moving_direction, speed, delta):
	velocity = moving_direction * speed * delta
	var collision = move_and_collide(velocity)
	return collision

func BounceBall(rebound_direction, speed, delta):
	var bounce_velocity = rebound_direction * speed * delta
	move_and_collide(bounce_velocity)

func _process(delta):
	if LaunchBall(Vector2(-50,10), 5, delta):
		BounceBall(Vector2(-50, 10) * -1, 5, delta)

I think I understand what is causing the problem:

  1. Upon receiving the CollisionObject2D, the if-statement returns true and it calls the BounceBall function with appropriate arguments.

  2. Variable bounce_velocity gets it’s value from passed arguments.

  3. Function move_and_collide gets called with parameter bounce_velocity → ball tries to move into different direction, but cannot since the _process function gets called again.

  4. Jittering starts

Honestly, i think my understanding of GDScript or the engine isn’t just good enough, which is why i am asking from here.

Thanks :slight_smile:

These function calls are your problem.

Once your ball collides it keeps changing directions.

This is whats really happening, i boiled the code down to make it easier to see.

func _process(delta):
	if move_and_collide(MOVE_LEFT):
		move_and_collide(MOVE_RIGHT)

It will move left fine, but on move left and collision. it will start moving right, but then in the next process frame it will start moving left again, collide and repeat every frame. (Jitter)

You need to track and maintain changes with the velocity variable. Dont set them as unchanging parameters to functions.

func _ready():
  #set initial velocity
  velocity = Vector2(-50,10) * 5 

func _process(delta):
    # move and collide the ball
	if move_and_collide(velocity * delta):
        # collided, bounce the ball
		velocity = -velocity # reverse direction
1 Like

Thank you for your reply! I’ll try your solution right away :pray: