线相交方法无法正常工作

时间:2014-01-09 06:07:19

标签: java math physics algebra calculus

我正在研究一些矢量数学,我需要计算多边形的法向量。 我的代码:

    //p is a parameter, is a Vec2, second point on first line
    double[][] vert = getVerticies(); //[any length, # of verticies][2]
    for(int i = 0; i < vert.length; i++) {
        Vec2 cm = Vec2.ZERO_VEC;//first point on first line, always is <0, 0> as it is the origin
        Vec2 rcm = getCM(); // just used to get relative positions.
        Vec2 v1 = cm.sub(new Vec2(vert[i])); //the first point in one of all edges of the shape, second line
        Vec2 v2 = cm.sub(new Vec2(i == vert.length - 1 ? vert[0] : vert[i + 1])); // the second point on the second  line.
        double den = (v2.getY() - v1.getY()) * (p.getX() - cm.getX()) - (v2.getX() - v1.getX()) * (p.getY() - cm.getY());
        if(den == 0D) {
            continue;
        }
        double a = ((v2.getX() - v1.getX()) * (cm.getY() - v1.getY()) - (v2.getY() - v1.getY()) * (cm.getX() - v1.getX())) / den;
        double b = ((p.getX() - cm.getX()) * (cm.getY() - v1.getY()) - (p.getY() - cm.getY()) * (cm.getX() - v1.getX())) / den;
        if(a >= 0D && a <= 1D && b >= 0D && b <= 1D) {
            Vec2 mid = v2.add(v2.sub(v1).scale(0.5D)); //this is just normal vector calculation stuff, I know the error isn't here, as if it was, it would return a non-unit-scale vector.
            return mid.uscale(); //hats the vector, returns
        }
    }
    return p; // return the parameter, second point on first line, used as a contingency, should never actually run, as the first line is fully contained in the lines were testing against

我做了一些调试,我只是看不到发生了什么。谁能告诉我数学有什么问题?它似乎流得绝对精细,但数学似乎并不正确。我对此代码的目标是确定我的线相交的两个顶点的索引。

2 个答案:

答案 0 :(得分:0)

哎呀,试图通过解释它来弄明白。我需要进行光线追踪,或使用光线相交测试。

答案 1 :(得分:0)

如果您正在尝试计算多边形的法线,看起来您正在尝试做一些过于复杂的事情。您可以简单地使用两个相邻边的交叉积来获得它。更好的是,使用简单的数学explained here,您甚至不需要计算边缘向量。只需取每个相邻顶点对的叉积并求它们:

enter image description here