0

I have a rudimentary collision detection function that tells me if two bounding boxes are overlapping. This post describes it well: Determine if two rectangles overlap each other? The code I use is simple and basically the same as the code from the post:

if (RectA.Left < RectB.Right && RectA.Right > RectB.Left &&
    RectA.Top > RectB.Bottom && RectA.Bottom < RectB.Top )

This works fine. My problem is, I need to know whether the collision occurred on the X or the Y-axis. This can be surmised from how much the boxes overlap on either axis: enter image description here

As you can see, there's more overlap occurring on the Y-axis (8 pixels) than on the X-axis (only 1 pixel). I can use this to determine the boxes are colliding on the X-axis, however, I haven't been able to come up with a concise and efficient way to do so. Any help is appreciated!

silver takana
  • 138
  • 12
Synthetix
  • 2,035
  • 3
  • 24
  • 30
  • 1
    What if the overlap is 1x1? IMO, there is not enough information in the raw overlap area alone - I think it needs to be based on the movement of the objects instead. – 0x5453 Feb 03 '22 at 20:29
  • Why don't you check more than one overlap? If in the next "frame" you have an X-overlap of still only 1 but a Y-overlap of e.g. 12, then the collision is obviously on the Y axis. – Yunnosch Feb 03 '22 at 20:29
  • @0x5453 Good question. If it's a 1x1 area, that's OK as I don't think hitting a corner will look weird with the resulting code. – Synthetix Feb 03 '22 at 20:31
  • @Synthetix My point is that a 1x1 overlap could be formed by *any* box moving in *any* direction (including the easy-to-miss edge case where a box is "cutting across" the corner of the other box). And 1x1 can be generalized to NxN. You don't have enough information to resolve the collision - I guarantee there are cases where it *will* look weird. – 0x5453 Feb 03 '22 at 20:39
  • @0x5453 I'm definitely open to other ways of doing this. If I need to use something like an object direction vector for a more accurate result, I can do that. I'm just trying to keep things as simple as possible. Can you suggest a fast way of checking the object trajectory? – Synthetix Feb 03 '22 at 23:55

1 Answers1

2

I suspect the premise of your question is what's tripping you up: collision direction is a product of the motion of the objects, not the size and shape of the overlap. You can't determine collision direction by analyzing a single frame.

As stated, your example does not provide enough information to determine the direction of collision. For example, if Box 2 was a fast-moving body, it might result in your above scenario by "jumping over" Box 1 while moving from the left. That might be an unlikely scenario in your game, but it emphasizes that you need to know how the objects are moving to determine your collision response.