判断两条线段相交的两种算法

来源:互联网 发布:sql blob大小 编辑:程序博客网 时间:2024/05/18 00:50
// Returns true if the lines between v0v1 and t0t1 cross// If the lines cross, the intersection between them will// be stored in intersectionPointbool linesCross(b2Vec2 v0, b2Vec2 v1, b2Vec2 t0, b2Vec2 t1, b2Vec2 &intersectionPoint){    if ( areVecsEqual(v1,t0) ||         areVecsEqual(v0,t0) ||         areVecsEqual(v1,t1) ||         areVecsEqual(v0,t1) )        return false;     b2Vec2 vnormal = v1 - v0;    vnormal = b2Cross(1.0f, vnormal);    float v0d = b2Dot(vnormal, v0);    float t0d = b2Dot(vnormal, t0);    float t1d = b2Dot(vnormal, t1);    if ( t0d > v0d && t1d > v0d )        return false;    if ( t0d < v0d && t1d < v0d )        return false;     b2Vec2 tnormal = t1 - t0;    tnormal = b2Cross(1.0f, tnormal);    t0d = b2Dot(tnormal, t0);    v0d = b2Dot(tnormal, v0);    float v1d = b2Dot(tnormal, v1);    if ( v0d > t0d && v1d > t0d )        return false;    if ( v0d < t0d && v1d < t0d )        return false;     intersectionPoint = v0 + ((t0d-v0d)/(v1d-v0d)) * (v1-v0);     return true;}


bool areVecsEqual(b2Vec2 v1, b2Vec2 v2) {    return v1.x == v2.x && v1.y == v2.y;}
struct pos{    double x ;    double y ;};struct line{    pos st ;    pos end ;};int n ;double Multiply(pos p1, pos p2, pos p0){    return ( (p1.x - p0.x) * (p2.y - p0.y) - (p2.x - p0.x) * (p1.y - p0.y) );}bool iscross(line L1, line L2){    return( (max(L1.st.x,   L1.end.x) >= min(L2.st.x, L2.end.x)) &&        (max(L2.st.x,   L2.end.x) >= min(L1.st.x, L1.end.x)) &&        (max(L1.st.y,   L1.end.y) >= min(L2.st.y, L2.end.y)) &&        (max(L2.st.y,   L2.end.y) >= min(L1.st.y, L1.end.y)) &&        (Multiply(L2.st, L1.end, L1.st) * Multiply(L1.end, L2.end, L1.st) >= 0) &&        (Multiply(L1.st, L2.end, L2.st) * Multiply(L2.end, L1.end, L2.st) >= 0)    );}

原创粉丝点击