I'm coding a small space Game in JavaScript, how do I detect collisions?
I am looping the Game with requestAnimationFrame() and my question is:
How do I detect a collision between two bodies, for the counting (death) Variable being incremented only once instead of continuously?
// --- Collision ---
asteroids.forEach(asteroid => {
//if (collisionOccured) { return; } I thought might work...
if (distance(spaceship.x + spaceship.width, spaceship.y + spaceship.width, asteroid.x, asteroid.y) < asteroid.radius + spaceship.width) {
console.log('Collision');
collisionOccured = true;
deaths++;
}
});
I think I understand what the problem is, the two bodies are colliding, so the distance between them is in n-Frames smaller than the condition, so the deaths variable more counts the Frames in which they are colliding than the number of collisions.
But how do I get it right? Any idea?
If it helps, here is the distance-function:
function distance(x1, y1, x2, y2) {
return Math.sqrt(Math.pow(Math.abs(x1 - x2), 2) + Math.pow(Math.abs(y1 - y2), 2));
}