1

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.

Ed Taylor
  • 108
  • 7

1 Answers1

1

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;
}
  • Thanks seems to have helped. Although now the balls are flying off screen. – Ed Taylor Aug 20 '17 at 15:07
  • You need to check both X and Y co-ordinates. But not independently. See here: http://cgp.wikidot.com/circle-to-circle-collision-detection – Milivoj Savin Aug 20 '17 at 15:09
  • I think there must be a problem with the loops because the balls now just go off screen so are obviously not being checked for those positions. – Ed Taylor Aug 20 '17 at 15:16
  • sorted now think they are working so just have to implement a better value than xPosition to detect collisions – Ed Taylor Aug 20 '17 at 15:35