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

    //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


我已经进行了一些调试,但看不到正在发生什么。谁能告诉我我的数学怎么了?似乎一切都很好,但是数学似乎并不正确。我使用此代码的目标是确定我的线相交的两个顶点的索引。

最佳答案

糟糕,是通过尝试对其进行解释的。我需要进行光线追踪或使用光线相交测试。

09-25 16:07