# Using dist(); for collision detection

**URL:** <https://discourse.processing.org/t/using-dist-for-collision-detection/40050>\
**Category:** Coding Questions\
**Tags:** homework\
**Created:** [December 7, 2022, 11:33am UTC](https://discourse.processing.org/t/using-dist-for-collision-detection/40050 "2022-12-07T11:33:32Z")\
**Posts on this page:** 1\
**Showing post:** 4

<div class="post-metadata">

**Author:** ![sableraph](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/sableraph/32/251_2.png) [@sableraph](https://discourse.processing.org/u/sableraph)\
**Post date:** [December 7, 2022, 12:25pm UTC](https://discourse.processing.org/t/using-dist-for-collision-detection/40050/4 "2022-12-07T12:25:27Z")

</div>

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

```auto
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:

```auto
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_

---

_[View the full topic](https://discourse.processing.org/t/using-dist-for-collision-detection/40050)._
