Let there be o object
s, and p projectile
s.
When testing for collision between any projectile
and any object
, is the fastest algorithm going to be order of n-squared?
Here's my pseudocode: (I'm actually writing this in C++, not a Python-like language)
for projectile p in projectiles:
for object o in objects:
if /* check distance between p and o */:
if /* collision */:
foo()
I know that when checking for collision in one set of objects, I can reduce the algorithm from T(n^2)
to T((n^2)/2)
by not "rechecking" objects, or checking the same two objects against each other twice. However, in this case, there are two sets of objects. I have never written algorithms for two sets of objects before. Is it "okay" for my algorithm in this situation to be O(n^2)
? Is there a fundamentally better way to go about this?
Notice
This question is NOT a duplicate of Collision detection of huge number of circles because that is talking about one set of objects. This question is entirely different.
If you do find a question involving two sets of objects --- not one set of objects --- please link to that question and then vote to close this question.
Why
Testing collision between two sets of objects is different than testing collision between one set of objects because:
When testing collision between one set of (sorted) objects, I can make the algorithm T((n^2)/2)
.
for(i = 0; i < length; ++i)
{
for(j = i + 1; j < length; ++j)
{
/* test collision between i and j */
}
}
Here's an example using indexes 1 through 5:
list: 1 2 3 4 5
1 - 2
1 - 3
1 - 4
1 - 5
2 - 3 /* notice this is NOT 2 - 1 */
2 - 4
2 - 5
3 - 4 /* again, this is NOT 3 - 1 or 3 - 2 */
3 - 5
4 - 5 /* finally, this is not 4 -1 or 4 - 2 or 4 - 3 */
This will take literally half the time that my algorithm for collision between two sets of objects takes. I know it doesn't change the big-O, but still, I think halving execution time is substantial. Here is my algorithm for collision between two sets of objects. It is T(n^2)
. I will explain.
for(i = 0; i < length; ++i)
{
for(j = 0; j < length; ++j)
{
/* test collision between i and j */
}
}
I believe you have to check every object against every other object. Because any projectile could be hitting any object, and we go through every projectile every time we go through one object. This algorithm could not be cut in half because we aren't testing projectiles against projectiles, or objects against objects.