Ed Taylor
Ed Taylor

Reputation: 108

Bouncing Balls in ArrayList Need to Detect Collisions

Hi I am making a BouncingBall program where the balls bounce off the walls and off each other. Walls is fine, but collisions are a problem. I am storing the Balls in an ArrayList so I can move any given number using a for each loop.

I have been unable to implement collisions and have looked a lot. The closest I can get is to where there are lots of random collisions when there shouldn't be.

Latest attempt: Physics Class to detect collisions and now the balls just run off screen..

public class Physics {

public static boolean Collision(BouncingBall b, ArrayList<BouncingBall> list){
    //boolean collide = false;
    for (int i = 0; i < list.size(); i++){

      if(b.getXPosition()== list.get(i).getXPosition()){
          return true;
      }

    }
    return false;
}

The bounce method itself(in class BallDemo):

                ball.draw();
                //above here is code to make balls and add to ArrayList
            }

            // make them bounce
            boolean finished =  false;

            while (!finished) {
                myCanvas.wait(50);

                for (BouncingBall ball: balls){


                    if(Physics.Collision(ball, balls)){
                        collisionCount(ball);
                    }



                    //if ball is out of X bounds bounce it back
                else if(ball.getXPosition()>=850 || ball.getXPosition()<0){
                        ball.collision();


                    }
                    //if ball is out of Y bounds bounce it back
              else if(ball.getYPosition()>=500 || ball.getYPosition()<0){
                        ball.yCollision();

                    }
                    ball.move();
                    }
                }
        }

Just to note:I am aware of the for loop having conflicts due to comparing the first ball with itself but have tried starting i at 1 and still doesn't work.

Upvotes: 1

Views: 496

Answers (1)

Milivoj Savin
Milivoj Savin

Reputation: 26

Since you are comparing each ball to the whole list, it will always collide with itself. You need to add a check in Collision to see if it's being compared with itself. Something like

if (b == list.get(i)) {
    continue;
}

Upvotes: 1

Related Questions