Circle Collision Javascript

与世无争的帅哥 提交于 2019-12-30 04:49:13

问题


Hello I need to make for school a program in Javascript that says if circles had an collision. It doesn't need to be shown graphical.

I gave it a try but my code doesn't seem to work.

Hope you could help me out with a script.

Here's my code what 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);

回答1:


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.

https://stackoverflow.com/a/8331460/128165




回答2:


In your if statement, try this instead:

if ( a * a > (x * x + y * y) ) {
    ...
} else {
    ...
}



回答3:


The length of a triangle having sides dx and dy (i.e. the distance between points (x1, y1) and (x2, y2) where dx = x2 - x1 and dy = y2 - y1) is equal to:

sqrt(dx^2 + dy^2)

So you probably want:

if(a > Math.sqrt(x*x + y*y)) {


来源:https://stackoverflow.com/questions/8331243/circle-collision-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!