Using dist(); for collision detection

The issue is that your code is only checking for a collision between the first second ball and the other balls:

if(dist(x[1], y[1], x[j], y[j]) < r)

You need to add a nested loop to check for collisions between all of the balls.

Here is an example of how you can do this:

for(int i = 0; i < ballCount; i++){
  for(int j = 0; j < ballCount; j++){
    if(i != j && dist(x[i], y[i], x[j], y[j]) < r){
      xSpeed[i] *= -1;
      ySpeed[i] *= -1;
      xSpeed[j] *= -1;
      ySpeed[j] *= -1;
    }
  }
}

This code checks for a collision between each pair of balls and reverses their speed if they are colliding. It also ensures that a ball does not collide with itself by checking if i and j are the same. You can add this code inside your gegner() function.

A more object oriented approach would be to create a Ball class with a method that takes an array of Balls and checks for collisions against all of them.

Note: part of this message was generated with ChatGPT

2 Likes