Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

This question already has an answer here:

I am trying to create a game in Pygame, with Python 3, and am trying to figure out an algorithm that will tell me which direction a rectangle is colliding with a rectangle, so that I can push it back the correct direction. I know I can detect rect-to-rect, and I could (possibly?) use pixel-to-pixel collision, but I was wondering if there was a better way. My collision algorithm currently loops through all of the "entity" objects in a Pygame sprite.Group(), and testing for collision using the colliderect() method, then I test which direction the rect is coming from by testing which sides overlap. Is there something similar that I could do with a collision between a triangle and a rectangle, too? Pseudocode would be nice

Rect from Bottom-Right Rect from Top-Right

share|improve this question

marked as duplicate by concept3d, Seth Battin, Josh Petrie Jan 6 '14 at 0:45

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1 Answer 1

up vote 1 down vote accepted

The safest way would be to find the intersection point of each of the 4 line segments of the rectangle with each of the 3 line segments of the triangle : if any of those is on the triangle and the rectangle, there's intersection. From the pictures you provided, though, it looks like we can assume the triangles are half rectangles, when a collision happens there's only one corner of the rectangle inside the triangle (no need to check for high speed and related sweeping), and every body nicely stays axis aligned.

This makes things simpler : If we call the triangle ABC, and the rectangle EFGH, first find the point D that makes ABCD a rectangle. If there's no rectangle collision between ABCD and EFGH, you know there won't be any between ABC and EFGH either. If there is, though, you still need to check that either E, F, G, or H (you can even possibly predict which one it will be) are on the same side of the line AC that B.

Point inside a triangle ABC if inside rectangle ABCD and in the same side of AC as B

If the assumptions are wrong please correct me, and if you need implementation details just ask.

share|improve this answer
    
Give me a while to implement this. When I get back, I will ask questions if I have any, then accept this answer. Thanks! –  Pip Jan 5 '14 at 16:39

Not the answer you're looking for? Browse other questions tagged or ask your own question.