JavaScript: find pairs from an object (not array) – collision detection

Home / Uncategorized / JavaScript: find pairs from an object (not array) – collision detection

Question:
I am building a game using Javascript and I need to do collision detection.

Everything drawn in the game has its own ID and stored in an object. I chose to use an object despite an array as a container because it is easy to delete children from it. When for example, a bullet hits a ship, it is removed from the object. But for an array, all of the children have to be shifted when one object is deleted. And it is nice to have IDs to keep track of everything.

In order to find pairs in an array, I can do this:var a = [];
//Object container

for(var i = 0; i < a.lenght; i++){ for(var j = i+1; j < a.lenght; j++){ var object1 = a[i]; var object2 = a[j]; //collision detection } } But for an object var o = {}; //Object container var progress = []; for(var key1 in o){ progress.push(key1); for(var key2 in o){ if(progress.indexOf(key2) === -1){ var object1 = a[i]; var object2 = a[j]; //collision detection } } } progress = []; This is a lot uglier than the array. Is there a better way?


Answer:
You could use Object.keys to get the property names in the object. Then it’s almost exactly like your array version:var keys = Object.keys(o); // *** Get the keys
for (var i = 0; i < keys.length; i++) { for (var j = i + 1; j < keys.length; j++) { var object1 = o[keys[i]]; // *** Main change is on var object2 = o[keys[j]]; // *** these two lines //collision detection } } Note that Object.keys only lists enumerable, own properties. Your for-in loop would visit all enumerable properties, even inherited ones. But I'm guessing your o doesn't have enumerable inherited properties. You only need to do Object.keys when you add or remove a ship, not every time you need to do collision detection. You'll need to profile it to determine whether using an object and rebuilding the keys array when you change it is more or less efficient than using an array and splice. Read more

Leave a Reply

Your email address will not be published. Required fields are marked *