views:

72

answers:

1

I've spent a good amount of time getting intersections working correctly between various 2D shapes (circle-circle, circle-tri, circle-rect, rect-rect - a huge thanks to those who've solved such problems from which I drew my solutions from) for a simple project and am now in the process of trying to implement an triangle-AABB intersection test.

I'm a bit stuck however. I've tried searching online and thinking it through however I've been unable to get any ideas. The thing that's given me the biggest issue at the moment is checking whether the edges of triangle (which is an isosceles btw) intersect the rectangle when no vertexes lie within the rectangle.

Any ideas how I could get this working?

EDIT: To give a bit more insight as to stages as I think they should occur:

1 - Check to see if any vertexes lie with in the rectangle (this part is easy). If yes, collision, otherwise continue.

2 - Check to see if any edges are intersecting the rectangle. This is where I'm stuck. I have little idea how to implement this.

+1  A: 

I'd calculate a collection of equations which define the 4 lines of the rectangle, and then solve against a collection of equations which define lines of the triangle.

For example, gievn a rectangle with lowest point (x1, y1) and one side having a gradient of g, one of the lines of the rectangle will be y = gx + y1. Find equations to represent the other 3 sides of the rectangle as well.

The lines which form the sides of the triangle will be calculated similarly. The equation for a line given two points is

y - y1 = (x - x1) * (y2 - y1)/(x2 - x1)

If there are any possible x & y values that satisy all 7 equations then you have an intersection.

edit: I realise that although this is a simple algorithm it might be tricky to code; another option is to calculate formulae for the intervals that form each edge (essentially lines with a min and max value) and solve these.

Kirk Broadhurst
The rectangle is axis-aligned (i.e. it's never going to be rotated). Would that simplify anything?
NRaf
Yes - it means that the formulae for the sides of the rectangle would be extremely simple, e.g. x > 5 and x < 10, y > 10 and y < 20. All you need to do is show that one of the edges of your triangles contains intersect one of the rectangle edges, e.g. x = 5 and 10 < y < 20, or y = 10 and 5 < x < 10, etc (there will be 4 combinations, for the four edges)
Kirk Broadhurst