#Detect if two lines overlap

1 messages · Page 1 of 1 (latest)

turbid narwhal
#

I want to be able to see if two LineRenderers are overlapping or not. In my game I'll have two kinds of lines: The one I'm currently drawing (endpoint is where the mouse is) and the ones that I've already defined (previously drawn)

Each line (apart from the one that the player is currently drawing) is stored in a static List<Line> where Line is just a class with two properties:

public class Line {
    public Vector2 StartPoint { get; set; }
    public Vector2 EndPoint { get; set; }
}

How could I detect if the currently drawn line is overlapping with any of the already defined lines in this List<Line>? I want to have a function in the Line class signed as bool Intersectes(Line otherLine). Any help is much appreciated! 😄

safe island
#

have you tried googling?
"check if 2 line segments intersect" gives multiple results, which are probably pretty optimal

turbid narwhal
#

I tried, but its just not working

#

I don't know why

#

This is what I had

public class Line
{
    public Vector2 startPoint;
    public Vector2 endPoint;

    private enum Orientation
    {
        Collinear, Clockwise, CounterClockwise
    }

    private bool OnSegment(Vector2 p, Vector2 q, Vector2 r)
    {
        return (q.x <= Mathf.Max(p.x, r.x) &&
                q.x >= Mathf.Min(p.x, r.x) &&
                q.y <= Mathf.Max(p.y, r.y) &&
                q.y >= Mathf.Min(p.y, r.y)
            );
    }

    private Orientation FindOrientation(Vector2 p, Vector2 q, Vector2 r)
    {
        float val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);

        switch (val)
        {
            case 0:
                return Orientation.Collinear;
            case < 0:
                return Orientation.CounterClockwise;
            default:
                return Orientation.Clockwise;
        }
    }

    public bool Intersects(Vector2 p1, Vector2 q1, Vector2 p2, Vector2 q2)
    {
        Orientation o1 = FindOrientation(p1, q1, p2);
        Orientation o2 = FindOrientation(p1, q1, q2);
        Orientation o3 = FindOrientation(p2, q2, p1);
        Orientation o4 = FindOrientation(p2, q2, q1);

        // General case
        if (o1 != o2 && o3 != o4)
            return true;

        // Special cases
        if (o1 == Orientation.Collinear && OnSegment(p1, p2, q1)) return true;
        if (o2 == Orientation.Collinear && OnSegment(p1, q2, q1)) return true;
        if (o3 == Orientation.Collinear && OnSegment(p2, p1, q2)) return true;
        if (o3 == Orientation.Collinear && OnSegment(p2, q1, q2)) return true;

        return false;
    }
}
#

Then I'd check like so:

if (_currentLine.Intersects(_currentLine.startPoint, line.startPoint, _currentLine.endPoint, line.endPoint))

(I also tried every possible combination of the parameters)

viscid mirage
#

The parameters are (_currentLine.startPoint, _currentLine.endPoint, line.startPoint, line.endPoint)

unreal kraken