智慧 + 毅力 = 无所不能

正确性、健壮性、可靠性、效率、易用性、可读性、可复用性、兼容性、可移植性...

导航

cocos2d-x 判断两条直线是否相交

Posted on 2014-08-25 21:58  Bill Yuan  阅读(617)  评论(0编辑  收藏  举报
bool GraphicsUtil::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;
}