Hello.
I'm doing a Pong game, and I got the bounce from the ball when it collides with the paddles.
But, as far I know, the angle which the ball enters and collides with the paddle is the same from the "exit", so the game now is a bit predictable and boring, especially if the game starts the ball with 0 degrees, it goes on horizontally forever between the paddles.

I want to add a little "randomness" to this exit angle when the ball hits the paddle, but I have no idea how to do it. I know it has something to do with the normal vector and the random functions godot has, but I have absolutely no idea how to implement and code it.

This is my code right now:

export var speed = 500
var velocity = Vector2.ZERO

func _ready() -> void:
    randomize()
    velocity.x = [-1,1][randi() % 2]
    velocity.y = [-0.7,0.7][randi() % 2]
    
func _physics_process(delta: float) -> void:
    var collision = move_and_collide(velocity * speed * delta)
    if collision:
        velocity = velocity.bounce(collision.normal)

You could try adding some random rotation based on the direction of the velocity. I’m away from my dev machine, so I cannot easily write code, but here’s the general idea I’d try:

  • Determine if the ball is moving left or right by looking at the sign of the X axis of the velocity. If the velocity is negative, then it should be moving left, while if it is positive, it should be right.
  • After determining the sign, you can then add rotation to the velocity using the rotated function.
  • to get a random angle, try something like var angle = deg2rad(rand_range(-10, 10)). This will offset it by 10 degrees.
  • Confirm the sign of the velocity on the X axis is still the same as it was prior to rotation, to ensure it is going in the right direction. If it is not, then the rotation flipped the direction horizontally. In this case, what I would do is use the original, non-rotated velocity.

Hopefully the above thought makes sense. If not, let me know and I’ll try to write some Godot pseudo code to show what I mean 🙂