Search code examples
collision-detection

OpenGL. Ball to ball collision


Making a probability machine in OpenGL.

Ball ballArray[5];

while(elapsed > 0)
{
     timeStep = m_Timer.getSeconds();
     for(int i = 0; i < NUMBER_OF_BALLS; ++i)
     {
        ballArray[i].updateBall(timeStep); // where collision with pegs dealt 
        //ballArray[0].ballBallCollision(timeStep,ballArray[0],ballArray[1]);
      }
      Redraw();
}

I can't get the commented line working :( How do I pass 2 instances of ball


Solution

  • Assuming ballBallCollision() works, you probably want to collide each ball with every other ball, i.e. 0 with 1, 0 with 2, 1 with 2 etc. You will need a second loop for this.

    My preferred solution is to create a loop that runs over all the remaining balls like this:

    for(int i = 0; i < NUMBER_OF_BALLS; ++i)
    {
       ballArray[i].updateBall(timeStep); // where collision with pegs dealt 
       for(int j = i + 1; i < NUMBER_OF_BALLS; ++j)
       {
          ballArray[i].ballBallCollision(timeStep,ballArray[i],ballArray[j]);
       }
    }
    

    Note that, since we start at i + 1, we never get a ball to collide with each other (0 with 0), and we don't check each pair twice (we check 0 against 1, but not 1 against 0 again).