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

// Returns true if the lines between v0v1 and t0t1 cross
// If the lines cross, the intersection between them will
// be stored in intersectionPoint
bool 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)
    );
}

 
 
 
 

转载于:https://www.cnblogs.com/tqj-zyy/archive/2013/01/22/4559829.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值