if you have an array of objects for example some balls in a Pool-Game. Then you may have a Problem to make collision detection between all these objects without loosing a lot of performance...
i will not describe here, how to do the collision-detection itself.. it is just a "system" to check an array of objects in a very "performance-friendly" way.
Maybe this is a guide for newbies... but i discovered this way myself and i was very proud of, so i wanted to share my experience with you
First. How do you think, you could do a collision detection between all those Objects in the array... sure.. for every Object do collision detection for all the others... this will look like this:
Code: Select all
const int OBJ_COUNT=30;
MyObject obj[OBJ_COUNT];
For(int i1=0;i1<OBJ_COUNT;i1++)
{
For(int i2=0;i2<OBJ_COUNT;i2++)
{
collisionCheck(obj[i1],obj[i2]);
};
};
so we add a litte modification to the code:
Code: Select all
const int OBJ_COUNT=30;
MyObject obj[OBJ_COUNT];
For(int i1=0;i1<OBJ_COUNT;i1++)
{
For(int i2=0;i2<OBJ_COUNT;i2++)
{
if(i1!=i2)
{
collisionCheck(obj[i1],obj[i2]);
};
};
};
The next step is to reduce useless checks...
for example in a pool-game, you don't have to check the balls, which aren't in the game anymore... so add a bool-var to the object-class and add this to the code:
Code: Select all
const int OBJ_COUNT=30;
MyObject obj[OBJ_COUNT];
For(int i1=0;i1<OBJ_COUNT;i1++)
{
if(obj[i1].active)
{
For(int i2=0;i2<OBJ_COUNT;i2++)
{
if(obj[i2].active && i1!=i2)
{
collisionCheck(obj[i1],obj[i2]);
};
};
};
};
if you analyse the code now.. you see, that some of the checks are made twice... for example:
i1=0; i2=1 -> collisionCheck(obj[0],obj[1]);
i1=1; i2=0 -> collisionCheck(obj[1],obj[0]);
looks very similar, right ?
and yes, it is absolutely useless to check the collision twice. it could reduce performance by about 50%.
But how can i prevent these double-checks ?
very easy... just chance this in the code:
Code: Select all
const int OBJ_COUNT=30;
MyObject obj[OBJ_COUNT];
For(int i1=0;i1<OBJ_COUNT;i1++)
{
if(obj[i1].active)
{
For(int i2=0;i2<OBJ_COUNT;i2++)
{
if(obj[i2].active && i1>i2)
{
collisionCheck(obj[i1],obj[i2]);
};
};
};
};
i1=0; i2=1 -> collisionCheck(obj[0],obj[1]);
i1=1; i2=0 -> collisionCheck(obj[1],obj[0]); //<- SKIPPED because i1<i2 !
and if i1 and i2 are the same value, it will also be skipped.
now, i'm quite sure, you can't optimize it more.
before i quit this "lesson" a litte hint:
if you use 2-dimensional arrays for your objects (for example [type][instance]) you have to use 4 for-loops, if you do it like my example. but in the second, you should use "i1<=i2" instead of "i1<i2". because if you set it to "i1<i2" the objects of the same type can't collide with each other..
i hope that someone can use it... and i hope i didn't overlook a similar tutorial like mine...
cheers