简体   繁体   English

JavaScript - 我不明白这个碰撞检测功能是如何工作的

[英]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.

相关问题 javascript async await 我不明白它是如何工作的 - javascript async await I don't understand how it works 我不明白这段代码在javascript中的工作方式 - I don't understand how this code works in javascript 我不明白这个javascript函数如何执行 - I don't understand how this javascript function executes 我不懂javascript中的函数返回 - I don't understand function return in javascript 我无法理解这个javascript函数是如何工作的 - I can't understand how this javascript function works 我是一个初学者,不了解我的代码是如何工作的(javascript) - I'm a beginner and I don't understand how my code works (javascript) 我不明白此代码“如何在javascript中的数组内编写uint32”的工作原理 - I don't understand how this code to “write an uint32 inside an array in javascript” works Javascript碰撞检测系统不会忽略阻塞的碰撞 - Javascript collision detection system don't ignore blocked collisions 我是否将 Jquery 事件侦听器正确转换为 Javascript? 我不明白 Javascript 如何在不针对 id 的情况下工作? - Did I convert my Jquery event listener into Javascript properly? I don't understand how the Javascript works without targeting the id? 我不明白这个javascript函数调用以及它将在何处使用 - I don't understand this javascript function call and where it would be used
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM