Removing reciprocal references from a 2D array
I have a 2D array that, for example, this:
[
[0, 1], // collisionGroup0's references
[0, 1, 2], // collisionGroup1's references
[0, 1], // collisionGroup2's references
];
This array defines a collision map for my game engine. So imagine I have 3 collision groups. From this array, I can tell the following:
collisionGroup0 collides with collisionGroup0 and collisionGroup1.
collisionGroup1 collides with collisionGroup0, collisionGroup1 and collisionGroup2.
collisionGroup2 collides with collisionGroup0 and collisionGroup1.
I hope that makes sense.
Okay, so the problem:
I'm looking for a way to loop through and remove the reciprocal references. Since collisionGroup0 collides with collisionGroup1 and collisionGroup1 collides with collisionGroup0, we only need the one reference. Otherwise we have (what's happening now in my engine) collisions being doubled up when I do the actual collision checks.
I'd like the final array, after processing, to look like this:
[
[0, 1], // collisionGroup0's references
[2], // collisionGroup1's references
[0, 1], // collisionGroup2's references
];
What I have now looks like this:
for (var row : int = 0; row < array.length; ++row)
{
for (var column : int = 0; column < array[row].length; ++column)
{
for (var row2 : int = row + 1; row2 < array.length; ++row2)
{
for (var column2 : int =开发者_Go百科 array[row2].length - 1; column2 >= 0; --column2)
{
if (array[row][column] == array[row2][column2])
array[row2].splice(column2, 1);
}
}
}
}
But that leaves me with this:
[
[0, 1], // collisionGroup0's references
[2], // collisionGroup1's references
[], // collisionGroup2's references
];
Because it doesn't take into account the fact that collisionGroup2 isn't reciprocal to collisionGroup0.
Any ideas what I'm missing?
Thanks!
Get rid of any collisions where the index of the target of the collision is greater than the current index. So, for instance, get rid of the ** guys below
[
[0, **1**], // collisionGroup0's references
[0, 1, **2**], // collisionGroup1's references
[0, 1], // collisionGroup2's references
];
because 1 > 0 and 2 > 1. You could do the opposite - but if they are in order, as in the example, this way you end up truncating the arrays, which is probably faster and easier than cutting off their heads.
I'm assuming the reciprocal references are always there. If not, this is useless!
精彩评论