Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Circle collision in JavaScript

For school I need to make a program in JavaScript that says if circles had a collision.

It doesn't need to be shown graphically.

I gave it a try, but my code doesn't seem to work. How can I fix it?

Here's the code I produced:

function collision (p1x, p1y, r1, p2x, p2y, r2) {
    var a;
    var x;
    var y;

    a = r1 + r2;
    x = p1x - p2x;
    y = p1y - p2y;

    if (a > (x*x) + (y*y)) {
        return true;
    } else {
        return false;
    }
}
var collision = collision(5, 500, 10, 1000, 1500, 1500);
alert(collision);
like image 711
RR_1990 Avatar asked Nov 30 '11 18:11

RR_1990


2 Answers

Your check should be if (a > Math.sqrt((x*x) + (y*y))) http://cgp.wikidot.com/circle-to-circle-collision-detection

So the complete code is

function collision(p1x, p1y, r1, p2x, p2y, r2) {
  var a;
  var x;
  var y;

  a = r1 + r2;
  x = p1x - p2x;
  y = p1y - p2y;

  if (a > Math.sqrt((x * x) + (y * y))) {
    return true;
  } else {
    return false;
  }
}
var collision = collision(5, 500, 10, 1000, 1500, 1500);
console.log(collision);

and for a less computational implementation (using ES7 syntax for the snippet) use

const checkCollision = (p1x, p1y, r1, p2x, p2y, r2) => ((r1 + r2) ** 2 > (p1x - p2x) ** 2 + (p1y - p2y) ** 2)

var collision = checkCollision(5, 500, 10, 1000, 1500, 1500);
console.log(collision);

as Darek Rossman shows in his answer.

like image 126
Gabriele Petrioli Avatar answered Sep 30 '22 14:09

Gabriele Petrioli


In your if statement, try this instead:

if ( a * a > (x * x + y * y) ) {
    ...
} else {
    ...
}
like image 32
Darek Rossman Avatar answered Sep 30 '22 12:09

Darek Rossman