I'm writing a 2d scrolling game in javascript using canvas and since I'm limited to setInterval running at minimum once every ms, I need to have some objects moving at greater than 1 pixel a second. I have this for collision detection between objects:
// ** oversee collisions
collisionsInterval = setInterval(function() {
// outter object
for(i = 0; i < objectsToCollision.length; i++) {
// inner object
for(j = 0; j < objectsToCollision.length; j++) {
// dont compare an object to itself
if(i==j) continue;
// check if they touch on x axis
if(Math.abs(objectsToCollision[i].centerX - objectsToCollision[j].centerX) <= (objectsToCollision[i].halfWidth + objectsToCollision[j].halfWidth)) {
// check if they touch on y axis
if(Math.abs(objectsToCollision[i].centerY - objectsToCollision[j].centerY) <= (objectsToCollision[i].halfHeight + objectsToCollision[j].halfHeight)) {
// a collision was detected, do something useful
alert();
}
}
}
}
}, 1);
The problem is, since it wont alert() when two things are about to touch because my objects move at more than 1px at a time. The problem is, some objects might move 3px at a time, some might move at 8px at a time, and I also have gravity occurring so in the Y direction especially the velocity of my objects will really vary.
In my code above objectsToCollision is an array which contains all the objects I'm checking for collisions with. I've modelled what I've done so far after this https://gamedev.stackexchange.com/a/587 but it doesn't discuss how to solve the problem I'm experiencing!