0

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));
}

1 Answers1

0

You can only increase the death count if there was not a previously detected collision.

if (distance(spaceship.x + spaceship.width, spaceship.y + spaceship.width, asteroid.x, asteroid.y) < asteroid.radius + spaceship.width) {         
    if (!collisionOccured) {
      console.log('Collision');
      collisionOccured = true;
      deaths++;
    }
}

if this does not work it is because collisionOccured is getting set to false at the begining of each frame and you should try to find a way to keep the value the variable had in the previous frame.

Albondi
  • 1,141
  • 1
  • 8
  • 19
  • Thanks for your quick response! But if I do it that way would it detect a next colision with an other asteroid? Maybe the collisionOccured variable has to be within the Asteroid class? – Niclas.rst Jan 02 '19 at 14:30
  • Yes, you can have a boolean "collided" in the asteroid class. But in that case if many asteroids are colliding you should still only increase the death count by 1 right? – Albondi Jan 02 '19 at 14:32
  • Yes would be great but it is not absolutely necessary. By the way, thank you very much for your help!! – Niclas.rst Jan 02 '19 at 14:40