views:

189

answers:

1

How can I programatically detect whether or not two triangles touch each other, given their vertices on a 2D coordinate plane? This includes touching points or edges, as well as if one triangle is completely "inside" the other one.

+1  A: 

Use Line Line intersection

http://www.topcoder.com/tc?module=Static&d1=tutorials&d2=geometry2#line_line_intersection

Also consider the possibility that some vertex might be touching one of the sides of the other triangle.

http://www.blackpawn.com/texts/pointinpoly/default.html

function SameSide(p1,p2, a,b)
    cp1 = CrossProduct(b-a, p1-a)
    cp2 = CrossProduct(b-a, p2-a)
    if DotProduct(cp1, cp2) >= 0 then return true
    else return false

function PointInTriangle(p, a,b,c)
    if SameSide(p,a, b,c) and SameSide(p,b, a,c)
        and SameSide(p,c, a,b) then return true
    else return false

Or look at this link and scroll down

http://compsci.ca/v3/viewtopic.php?t=6034

Hamish Grubijan
This doesn't check if one triangle is completely inside another one, though, does it.
SpikeX
Dave
For that you need to make sure that all 3 vertices are on the edges or inside the triangle. Let me find a link. Meanwhile, feel free to upvote.
Hamish Grubijan
Well, it may not be pretty, but I can combine your "PointInTriangle" function with a Line-Line-detection function to get what I need. (My first comment here was before the post was edited). Thanks.
SpikeX
Cool. If you want to make this super-optimized at the expense of readability, consider writing unit tests first before hacking away at code to make it faster.
Hamish Grubijan