Code Vonc

Intersection de segments 2D

CommentairesComments

Déterminer si deux segments 2D se croisent.


def IntersectionSegments2DBool(p, p2, q, q2) :

    def ccw(p, p2, q) :
        return (q.y - p.y) * (p2.x - p.x) > (p2.y - p.y) * (q.x - p.x)
    
    return ccw(p, q, q2) != ccw(p2, q, q2) and ccw(p, p2, q) != ccw(p, p2, q2)

Source


Calculer le point d'intersection entre deux segments 2D.


def IntersectionSegments2DVector(p, p2, q, q2) :
    
    def CrossScal(a, v) :
        return a.x * v.y - a.y * v.x;
    
    r = p2 - p
    s = q2 - q
    rxs = CrossScal(r, s)
    qpxr = CrossScal((q - p), r)

    if rxs == 0. :
        return None

    t = CrossScal((q - p), s) / rxs
    u = CrossScal((q - p), r) / rxs

    if (0 <= t and t <= 1) and (0 <= u and u <= 1) :
        return p + t*r

    return None

Source