I am working on an Android game and I have two objects A and B (both rectangles) and when they collide I simply want to know which side of B was hit. I have detected the collision fine, but I am having trouble figuring out which side of the rectangle B took the hit? Any ideas? Thanks!
You can calculate the centroid (it's easy to calculate, google for a formula) of both rectangles and compare them.
I'm saying this, because it's a general solution, i have no idea how you do your collision detection, there are plenty of variables here like size and speed of the rectangles (if your rectangles move too fast and you're not doing sweep testing, then you might "overshoot" and it'll look like the collision was from the other side). It's not the most elegant solution either, but you only do this once when the collision happens, so it shouldn't be too bad, though that depends on the amount of collisions. You're not giving enough information.
I suggest computing the Minkowski sum of B and A, which is a new rectangle, and checking where the centre of A lies relatively to the diagonals of that rectangle:
Edit: use Minkowski sum and fix variable names
|show 2 more comments|
Compare A and B to see where they are in regards to each other.
A width 20 height 20 A xmin + pos, xmax + pos A ymin + pos, ymax + pos
Same above for B.
if A xmax + pos (left side) < B xmin + pos A is on left of B, B left side hit..
Are you using the Rect class? http://developer.android.com/reference/android/graphics/Rect.html
If so, some simple comparisons will left you know which side collided... From the Rect class, you have attributes for the top (or North), the bottom (or South), the left (or West), and the right (or East).
For example, this test will determine if rectB's left side crossed rectA's right side:
Remember that rectB could collide with two sides. Image rect B's lower left hand corner crossing over rect A's upper right...rect B would've crossed over rectA's top and right edges.
Remember that if rectB is completely inside rectA, that would look like it crossed over all four sides of rectA!