简体   繁体   English

为什么此功能无法检测到重叠的圆?

[英]Why doesn't this function detect overlapping circles?

http://jsfiddle.net/goldrunt/SeAGU/52/ Line 49 checks for "false" on isOnCircle function before creating the new object. http://jsfiddle.net/goldrunt/SeAGU/52/第49行在创建新对象之前检查isOnCircle函数上的“ false”。 Function is on line 32. When creating more object, the function is passing when it should not pass. 函数在第32行。创建更多对象时,函数在不应该传递的情况下正在传递。

 if (isOnCanvas(location) && !isOnCircle(location)) {
        console.log(location, isOnCanvas(location), isOnCircle(location));
        create(location);

In fact I can't get the collision detection to register true no matter what values are passed to it 实际上,无论将什么值传递给碰撞检测,我都无法将其注册为true

(Math.pow((a.x - i.x), 2) + Math.pow((a.y - i.y), 2) <= Math.pow((a.radius + i.radius), 2))

here I've fixed and given more descriptive variable names so you can see what's going on. 在这里,我已经修复并给出了更多描述性的变量名称,以便您了解发生了什么。 EDIT: I've noticed you don't always feed a circle but sometimes a point as A, which does not have a .radius property resulting in NaN, which also screws up your comparison. 编辑:我注意到您并不总是进给一个圆,而是有时将一个点作为A,它不具有导致NaN的.radius属性,这也弄乱了您的比较。

function circleTest(a,b) {
    var DistanceX = a.x - b.x;
    var DistanceY = a.y - b.y;
    var DistanceCenter = Math.sqrt(DistanceX * DistanceX + DistanceY * DistanceY);
    var CollisionDistance = b.radius;
    if (a.radius) CollisionDistance += a.radius
    return DistanceCenter <= CollisionDistance;
}

I also noticed a problem in your function called "isOnCircle" where you are using i (a number) as if it were a circle object, with the above function this can be fixed like: 我还注意到您的函数“ isOnCircle”中存在一个问题,其中您使用i(一个数字)就好像它是一个圆形对象一样,使用上述函数可以将其固定为:

function isOnCircle(a) {
    for (var i = 0; i < circles.length; i++) {
        if (circleTest(a, circles[i])) return true;
    }
    return false;
}

Two problems: 两个问题:

  • i is the numerical index you are using to iterate through the circles array but you are using it as if it was a circle object; i是您正在使用通过迭代数值索引circles阵列,但正在使用的话,就好像它是一个圆对象; you need to use circles[i] to get the circle at each iteration. 您需要使用circle circles[i]在每次迭代时获取圆。
  • a is a point and does not have a radius (in the code below I've left a.radius in just in-case you pass in a circle rather than a point and have OR ed it with 0 so you get a valid number). a是一个点并且没有半径(在下面的代码中,我留了a.radius ,以防万一您绕圆而不是一个点并用0进行OR ,以便获得有效的数字) 。

Defining some additional variables (for clarity) then you can replace the isOnCircle function with this: 定义一些其他变量(为清楚起见),然后可以用以下方法替换isOnCircle函数:

function isOnCircle(a) {
    var i=0,l=circles.length,x,y,d,c;
    for (; i < l; ++i) {
        c = circles[i];
        x = a.x-c.x;
        y = a.y-c.y;
        d = (a.radius||0)+c.radius;
        if (x*x+y*y <= d*d) {
            return true;
        }
    }
    return false;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM