【问题标题】:In polygon test, hit test, is a point in a polygon? method在多边形测试中,命中测试中,一个点是多边形吗?方法
【发布时间】:2011-10-23 19:02:08
【问题描述】:

我创建了一个名为 isInPoly 的方法,它接收 2 条线的 x 和 y 坐标(因此是 8 个坐标)并确定 2 条线相交的位置。我知道我应该调用类似 intersectLocation 之类的方法,但创建它的原因是查看一个点是否在多边形中。如果您知道一个不在多边形中的点,并在该点和您要测试的点之间划一条线以查看它是否在多边形内,然后计算有多少交叉点。如果交叉点的数量是偶数,则该点不在多边形中,如果数量是奇数,则该点在多边形中。无论如何,我没有得到这种方法的正确输出。如果测试点与已知点的斜率为 -1,我的程序仅向我显示该点位于多边形内部。我知道我刚才写的可能很难理解,你看看我的方法有没有问题?

public static boolean isInPoly(float l1x1, float l1y1, float l1x2, float l1y2, float l2x1, float l2y1, float l2x2, float l2y2) {
    // TODO Auto-generated method stub

    // l1x1 = the first lines first x coordinate 
    // l1y1 = the first lines first x coordinate 
    //.....
    //l1m = the first lines slope represented as "m" in the equation y=mx+b
    //l1b = the first lines y intercept represented as "b" in the equation y=mx+b
    // x = the x coordinate of the intersection on the 2 lines  
    // y = the x coordinate of the intersection on the 2 lines 



    float l1m,l2m,l1b,l2b,x,y;

    //y=mx+b
    //x=(y2-y1)/(x2-x1)
    //b=y/(mx)


    //slopes of each line
    l1m = (l1y2-l1y1)/(l1x2-l1x1);
    l2m = (l2y2-l2y1)/(l2x2-l2x1);

    //y-intercepts of each line
    l1b = l1y2/(l1m*l1x2);
    l2b = l2y2/(l2m*l2x2);

    //m1x+b1=m2x+b2
    //m1x=m2x+b2-b1
    //x=(m2/m1)x+((b2-b1)/m1)
    //x-(m2/m1)x=((b2-b1)/m1)
    //(1-(m2/m1))x=((b2-b1)/m1)
    //x=((b2-b1)/m1)/(1-(m2/m1))


    //finding the x coordinate of the intersection
    x=((l2b-l1b)/l1m)/(1-(l2m/l1m));

    //y=mx+b


    //finding the x coordinate of the intersection
    y=(l1m*x)+l1b;

    if(y>=l1y1 && y<=l1y2  && x>=l1x1 && x<=l1x2){
        return true;
    }
    else{
        return false;
    }

}

【问题讨论】:

    标签: java android testing polygon hit


    【解决方案1】:

    斜率计算是对的。

    但是b方程变换是错误的。应该是:

    //l1y1=l1m*l1x1+l1b
    l1b=l1y1-l1m*l1x1
    

    x 坐标的计算也是错误的(编辑:事实上它是正确的,但比必要的复杂)。正确的转换是:

    //l1m*x+l1b = l2m*x+l2b
    //l1m*x-l2m*x = l2b-l1b
    // x*(l1m-l2m) = l2b - l1b
    x = (l2b-l1b) / (l1m-l2m)
    

    算法的其余部分是正确的。但也请记住,您还必须考虑完全相同的线(无限交叉点)之类的事情。并且还可以在方程中捕获除零异常(例如),用于平行于 y 轴的线。

    if 子句中的验证仅对某些行有效。您可能还考虑到线的坐标可能会交换,因此交叉点的 x 坐标始终必须小于线的两个 x 坐标的最大值并大于 x 坐标的最小值。 y 坐标也是如此。

    x_max = l1x1 > l1x2 ? l1x1 : l1x2;
    x_min = l1x1 < l1x2 ? l1x2 : l1x1;
    
    y_max = l1y1 > l1y2 ? l1y1 : l1y2;
    y_min = l1y1 < l1y2 ? l1y2 : l1y1;
    
    if ((y_min <= y) && (y_max => y) && (x_min <= x) && (x_max >= x))
        return true;
    

    【讨论】:

      猜你喜欢
      • 2019-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多