Search code examples
javacollision-detection

Collision between balls


I have a method that reflects balls against a wall, and also each other. The radius of each ball is 50.

public void reflectBalls(){
    for(int j = 0; j < 2; j++){
        if(ball[j].getY() <= NWall) ball[j].flipVertical();
        else if(ball[j].getY() >= (SWall - 50)) ball[j].flipVertical();
        else if(ball[j].getX() <= WWall) ball[j].flipHorizontal();
        else if(ball[j].getX() >= (EWall - 50)) ball[j].flipHorizontal();
    }
    for(int i = 0; i < 2; i++){
        for(int j = 0; j < 2; j++){
            if(i == j){
                continue;
            }else{
                double ax = (double)ball[i].getX();
                double ay = (double)ball[i].getY();
                double bx = (double)ball[j].getX();
                double by = (double)ball[j].getY();
                double distx = (ax-bx)*(ax-bx);
                double disty = (ay-by)*(ay-by);
                double distance = Math.sqrt(distx + disty);
                if(Math.floor(distance) <= 100){
                    ball[i].flipHorizontal();
                    ball[j].flipVertical();
                    ball[i].flipVertical();
                    ball[j].flipHorizontal();
                }
            }
        }
    }
}

The first part (reflection against walls) works perfectly fine. However, the balls do not collide; they just pass through each other. I've tried many different ways, but maybe there's some sort of math I am missing. My algorithm works based on the Pythagorean theorem, where the difference between X coordinates and the difference between the Y coordinates are each squared, and their sum is the distance between the centers.


Solution

  • Here is your problem - you find that ball i collides with ball j and you flip it. Then you find that ball j collides with ball i and flip them again. As a result no collision happens. Only perform the collision check if j > i and all should be fine.