9

ボックス内のマウスヒットを検出するためのレイキャスティングアルゴリズムの不正確さに問題がありました。私はこれを適切に修正する方法について完全に途方に暮れていて、それは何週間も私を悩ませてきました。

この問題は、画像([0、0、-30]を中心とするボックス)で最も簡単に説明できます。

問題のスクリーンショット

黒い線は実際に描かれたヒットボックスを表し、緑のボックスは実際にヒットしたように見えるものを表します。オフセット(ボックスが原点から離れていると大きくなるように見える)であり、描画されたヒットボックスよりもわずかに小さいことに注意してください。

関連するコードは次のとおりです。

レイボックスキャスト:

double BBox::checkFaceIntersection(Vector3 points[4], Vector3 normal, Ray3 ray) {

    double rayDotNorm = ray.direction.dot(normal);
    if(rayDotNorm == 0) return -1;

    Vector3 intersect = points[0] - ray.origin;
    double t = intersect.dot(normal) / rayDotNorm;
    if(t < 0) return -1;

    // Check if first point is from under or below polygon
    bool positive = false;
    double firstPtDot = ray.direction.dot( (ray.origin - points[0]).cross(ray.origin - points[1]) );
    if(firstPtDot > 0) positive = true;
    else if(firstPtDot < 0) positive = false;
    else return -1;

    // Check all signs are the same
    for(int i = 1; i < 4; i++) {
        int nextPoint = (i+1) % 4;
        double rayDotPt = ray.direction.dot( (ray.origin - points[i]).cross(ray.origin - points[nextPoint]) );
        if(positive && rayDotPt < 0) {
            return -1;
        }
        else if(!positive && rayDotPt > 0) {
            return -1;
        }
    }

    return t;
}

光線へのマウス:

GLint viewport[4];
GLdouble modelMatrix[16];
GLdouble projectionMatrix[16];

glGetIntegerv(GL_VIEWPORT, viewport);
glGetDoublev(GL_MODELVIEW_MATRIX, modelMatrix);
glGetDoublev(GL_PROJECTION_MATRIX, projectionMatrix);

GLfloat winY = GLfloat(viewport[3] - mouse_y);

Ray3 ray;
double x, y, z;
gluUnProject( (double) mouse_x, winY, 0.0f, // Near
              modelMatrix, projectionMatrix, viewport,
              &x, &y, &z );
ray.origin = Vector3(x, y, z);

gluUnProject( (double) mouse_x, winY, 1.0f, // Far
              modelMatrix, projectionMatrix, viewport,
          &x, &y, &z );
ray.direction = Vector3(x, y, z);

if(bbox.checkBoxIntersection(ray) != -1) {
    std::cout << "Hit!" << std::endl;
}

実際の光線を線で描いてみましたが、描いた箱と正しく交差しているようです。

ボックスの位置によってすべてのポイントと光線の原点/方向を差し引くことでオフセットの問題を部分的に修正しましたが、なぜそれが機能し、ヒットボックスのサイズが依然として不正確なままであるのかわかりません。

アイデア/代替アプローチはありますか?必要に応じて提供する他のコードがあります。

4

1 に答える 1

11

あなたは間違った方向を想定しています。正解は次のとおりです。

ray.direction = Vector3(far.x - near.x, far.y - near.y, far.z - near.z);

近距離と遠距離の交点を差し引かないと、方向がずれます。

于 2012-02-23T09:46:22.600 に答える