-1

我正在尝试对三角形的三个点进行排序,以便成功地将其添加到物理引擎中。在 x 轴上位置小于 0.0 的所有三角形都正确显示。但是,在那之后,第一个元素 ( v[0]) 总是设置为 { 0.0, 0.0},其余的似乎还可以。这是我进行排序和添加的主要功能。

void Core::addPoly(float x1, float y1, 
                   float x2, float y2, 
                   float x3, float y3) {

    std::vector<PVector> v(3);
    v.push_back(PVector(x1, y1));
    v.push_back(PVector(x2, y2));
    v.push_back(PVector(x3, y3));

    PVector center((x1+x2+x3)/3, (y1+y2+y3)/3);

    std::sort(v.begin(), v.end(), [center](PVector b, PVector a) { 
        if (a.x >= 0 && b.x < 0)
            return true;
        if (a.x == 0 && b.x == 0)
            return a.y > b.y;

        // compute the cross product of vectors (center -> a) x (center -> b)
        float det = (a.x-center.x) * (b.y-center.y) - (b.x - center.x) * (a.y - center.y);
        if (det < 0)
            return true;
        if (det > 0)
            return false;

        // points a and b are on the same line from the center
        // check which point is closer to the center
        float d1 = (a.x-center.x) * (a.x-center.x) + (a.y-center.y) * (a.y-center.y);
        float d2 = (b.x-center.x) * (b.x-center.x) + (b.y-center.y) * (b.y-center.y);
        return d1 > d2;
    });

    emap->polys.push_back(Polygon(v[0], v[1], v[2]));
}

我正在使用此处提供的排序功能。它最初将所有三角形的第一个元素指向中心(但是我不相信这是正确的行为)-我在 lambda 声明中切换了 a 和 b,现在它仅在 x 轴上的 0.0 之后显示。

如果我们有 3 个三角形传入(想象 | 在平面上是 0.0 和 ___ 是 0.0)

^     |
    ^ |   ^
______|_____________

第三个三角形的第 0 个顶点实际上会变成这样:

^     |
    ^ |  ___/|
______|_/______________

(这应该是一个三角形)

但是,0.0 从未传递给 addPoly。

4

1 回答 1

1

这一行:

std::vector<PVector> v(3);

使您的向量使用三个<0.0,0.0>值进行初始化。将其更改为

std::vector<PVector> v;

应该解决您的问题。

代码似乎是这样工作的:

struct PVector 
{ 
    float x; 
    float y; 
    PVector(float x, float y) : x(x),y(y){}
    PVector() : x(0.0f), y(0.0f) {}
};


static void addPoly(float x1, float y1, 
                   float x2, float y2, 
                   float x3, float y3) {

    std::vector<PVector> v;
    v.push_back(PVector(x1, y1));
    v.push_back(PVector(x2, y2));
    v.push_back(PVector(x3, y3));

    PVector center((x1+x2+x3)/3, (y1+y2+y3)/3);

    std::sort(v.begin(), v.end(), [center](PVector b, PVector a) -> bool { 
        if (a.x >= 0 && b.x < 0)
            return true;
        if (a.x == 0 && b.x == 0)
            return a.y > b.y;

        // compute the cross product of vectors (center -> a) x (center -> b)
        float det = (a.x-center.x) * (b.y-center.y) - (b.x - center.x) * (a.y - center.y);
        if (det < 0)
            return true;
        if (det > 0)
            return false;

        // points a and b are on the same line from the center
        // check which point is closer to the center
        float d1 = (a.x-center.x) * (a.x-center.x) + (a.y-center.y) * (a.y-center.y);
        float d2 = (b.x-center.x) * (b.x-center.x) + (b.y-center.y) * (b.y-center.y);
        return d1 > d2;
    });

    //emap->polys.push_back(Polygon(v[0], v[1], v[2]));
}
于 2013-01-19T04:51:50.653 回答