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.

Author: Daniel X

Heretic priest of the Machine God. I enjoy crawling around in Jeff Bezo's spaceship, bringing technology to the people, and long walks outside of time and space.

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.

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s