'Triangles intersection

I'm working on a 2D physics engine for polygons. What troubles me is finding triangle-triangle intersection. I'm combining three points to make up the triangles (x1,y1), (x2,y2), (x3,y3) or points a, b, and c, which is done for both of the triangles.

How would I use the points to find if the two triangles are overlapping? Bonus points if you can find the location of the collision giving the direction they are traveling.



Solution 1:[1]

I finally got a decent algorithm that finds the closest path between two general triangles.

fig

See the full C# code on GitHub and some highlights below

Geometry Classes

public readonly struct Triangle 
{
    public Vector2 A { get; }
    public Vector2 B { get; }
    public Vector2 C { get; }
    public bool Contains(Vector2 point) { }
    public Contact GetClosestPoints(Vector2 other) { }
    public Contact GetClosestPoints(Side other) { }
    public Contact GetClosestPoints(Triangle other) { }
}

public readonly struct Side
{
    public Vector2 A { get; }
    public Vector2 B { get; }
    public bool Contains(Vector2 point) { }
    public Contact GetClosestPoints(Vector2 other) { }
    public Contact GetClosestPoints(Side other) { }
}

public readonly struct Line
{
    public float A { get; }
    public float B { get; }
    public float C { get; }
    public bool Contains(Vector2 point) { }
    public Vector2 Project(Vector2 point) { }

}

public readonly struct Contact 
{
    public Contact(Vector2 source, Vector2 target)
    {
        Source = source;
        Target = target;
    }
    public Vector2 Source { get; }
    public Vector2 Target { get; }
    public Vector2 Direction { get => { }; }
    public float Distance { get => { }; }

    public Contact Flip() => new Contact(Target, Source);
}

Algorithm

Finding the closest points between to triangles, involves the following steps

  1. Find closest points of triangle A to each of the following 6 geometries from triangle B
  • Take each vertex of triangle B and find the closest point to triangle A
    1. Find distances to each vertex of triangle A
    2. Find distances to each side of triangle A.
    3. The closest point might be on the side, or on one of the ends of the sides
  • Take each side of triangle B and find the closest point to triangle A
    1. Find distances to each vertex of triangle A. The closest point might be on the side or on one of the ends
    2. Find distances of the ends of the sides to triangle A
  1. Sort through each of the 6 distances and pick the smallest value
  2. Match the smallest value to the geometry element.
  3. Create a Contact object with the matching pair of closest points.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1