[英]JavaScript - I don't understand how this collision detection function works
I'm enrolling in this course and they have this function from their code example and I don't understand how this particular one works. 我正在注册这个课程 ,他们从他们的代码示例中获得了这个功能,我不明白这个特定的工作原理。
function circRectsOverlap(x0, y0, w0, h0, cx, cy, r) {
var testX=cx;
var testY=cy;
if (testX < x0) testX=x0;
if (testX > (x0+w0)) testX=(x0+w0);
if (testY < y0) testY=y0;
if (testY > (y0+h0)) testY=(y0+h0);
return (((cx-testX)*(cx-testX)+(cy-testY)*(cy-testY))< r*r);
}
The first four arguments are the x and y position, width and height of the rectangle, while the last three are the x and y position, and the radius of the circle in the canvas. 前四个参数是矩形的x和y位置,宽度和高度,而后三个是x和y位置,以及画布中圆的半径。
If the rectangle and circle touch, the function returns true
, hence there is a collision. 如果矩形和圆形触摸,则该函数返回
true
,因此存在碰撞。
It appears that testX and testY become the coordinates of the nearest point to the center of the circle enclosed by the rectangle. 看来testX和testY成为矩形所包围的圆心的最近点的坐标。 The four if tests 'clamp' these values to the edges of the rectangle should the center of the circle be outside of it in either dimension.
如果测试将这些值“钳制”到矩形的边缘,则四个圆圈的中心应该在任一维度上都在圆的中心。 It might help to consider the case where the circle is centered inside the rectangle - all the ifs are false and testX and testY are the coordinates of the circle's center.
考虑圆在矩形内部居中的情况可能会有所帮助 - 所有ifs都是false,testX和testY是圆心的坐标。 The test in the return statement uses the Pythagorean Theorem to determine if the test point is within the radius of the circle.
return语句中的测试使用Pythagorean定理来确定测试点是否在圆的半径范围内。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.