Circular Collision Detection in JavaScript

Collision detection is the core of many games and simulations. It is therefore important to have a simple and efficient collision detection algorithm.

This algorithm uses circles as the basis for colliding elements.

function collision(c1, c2) {
  var dx = c1.x - c2.x;
  var dy = c1.y - c2.y;
  var dist = c1.radius + c2.radius;
  return (dx * dx + dy * dy <= dist * dist)

Envisioning it graphically shows how the inequality relates to the Pythagorean Theorem.

3 thoughts on “Circular Collision Detection in JavaScript

  1. Nice! I love how concise this was. I’m making pong in javascript and I’ll have to ome up with something similar for detecting collision with box against circle.

    Thanks for this.

Leave a Reply

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