[英]Circle collision in JavaScript
For school I need to make a program in JavaScript that says if circles had a collision.对于学校,我需要用 JavaScript 编写一个程序,说明圆圈是否发生碰撞。
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);
Your check should be if (a > Math.sqrt((x*x) + (y*y)))
http://cgp.wikidot.com/circle-to-circle-collision-detection你的检查应该是
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对于计算量较少的实现(对代码段使用 ES7 语法)使用
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 .正如 Darek Rossman 在他的回答中所示。
In your if statement, try this instead:在你的if语句中,试试这个:
if ( a * a > (x * x + y * y) ) {
...
} else {
...
}
The length of a triangle having sides dx
and dy
(ie the distance between points (x1, y1)
and (x2, y2)
where dx = x2 - x1
and dy = y2 - y1
) is equal to:边为
dx
和dy
的三角形的长度(即点(x1, y1)
和(x2, y2)
之间的距离(x2, y2)
其中dx = x2 - x1
和dy = y2 - y1
)等于:
sqrt(dx^2 + dy^2)
So you probably want:所以你可能想要:
if(a > Math.sqrt(x*x + y*y)) {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.