0

I can't for the life of me figure out how to get it to return true if the segments cross. Any help would be greatly appreciated.

bool doCross(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4)
{
    bool cross = true;
    double denom, uA, uB;

    denom = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1);

    if(denom == 0)
    {
        cross = false;
    }
    else
    {
        uA = (x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3) / denom;
        uB = (x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3) / denom;
    }
    if (abs(0 < uA) && abs(uA < 1) && abs(0 < uB) && abs(uB < 1))
    {
        cross = true;
    }
    else
    {
        cross = false;
    }       
    return cross;   
}
4

2 に答える 2

3

2 つの線分ABCDは、 ABが交差し、 CDの異なる側にあり、その逆もあります。点Xが有向線分PQの左側にあるかどうかをテストするには、 ccwプリミティブを使用します。一部のコードについては、http://algs4.cs.princeton.edu/91primitives/ の線分の交差と、http://www.cs.princeton.edu/~rs/AlgsDS07/16Geometric.pdfのスライドを参照してください

于 2012-09-13T23:57:14.097 に答える
2

あなたが言った:

uA = (x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3) / denom;
uB = (x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3) / denom;

私はあなたが欲しいと思います:

uA = ((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)) / denom;
uB = ((x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)) / denom;

あなたが言った:

if (abs(0 < uA) && abs(uA < 1) && abs(0 < uB) && abs(uB < 1))

あなたは比較の絶対値を取っていますが、それはまったく意味がありません。よかった:

if ((0 < abs(uA)) && (abs(uA) < 1) && (0 < abs(uB)) && abs(uB) < 1))

float / doubleを比較するときに整数定数を使用することは、必ずしもエラーではありませんが、悪い形式です。

于 2012-09-14T00:01:35.583 に答える