My question regards speed when there are lots of objects. Right now, the game checks all objects (circles) against all objects to see if there is a collision. I was originally gonna divide space up in to grids (squares) and check each item against all items in its grid and (8) adjacent grids. However, I got to thinking...checking to see if the distance is less than the sum of the radii is not that bad, and dividing into grids WILL consume resources. So to test the theory of "leaving it how it is is okay" I added one hundred objects (so each checking against every other is running through this code something like 100*100/2 times, a lot!). However, it still ran fine.
So the question is: Do I just need to add more objects to experience the slow-down that dividing into grids will save me from? Or will dividing the area into grids not provide a significant advantage/actually be worse than my current method?
Relevant code is below:
Code: Select all
for (int counter1 = 0; counter1 < PhysicsApplet.mastercounter-1; counter1++) { //run all moveable
for (int counter2 = counter1+1; counter2 < PhysicsApplet.mastercounter; counter2++) //run through all the ones that have not been check against it yet (anything above it on the list)
{
srad = PhysicsApplet.masterlist[counter1].radius + PhysicsApplet.masterlist[counter2].radius; //sum radii
dis = Math.sqrt((PhysicsApplet.masterlist[counter1].x_pos - PhysicsApplet.masterlist[counter2].x_pos)*(PhysicsApplet.masterlist[counter1].x_pos - PhysicsApplet.masterlist[counter2].x_pos) + (PhysicsApplet.masterlist[counter1].y_pos - PhysicsApplet.masterlist[counter2].y_pos)*(PhysicsApplet.masterlist[counter1].y_pos - PhysicsApplet.masterlist[counter2].y_pos));
if (srad > dis) { //if true then collision
-Computational Physics Newbie

P.S. I am eventually gonna do some sort of trajectory analysis to avoid fast objects going through each other, but my question has nothing to do with that issue, for now I am satisfied with the "if its touching during the frame then collision" algorithm.