-1

http://jeffreythompson.org/collision-detection/rect-rect.php

I am trying to figure out the algorithm of the collision detection of the rectangle/rectangle with the rectangles' picture and code. According to Jeff Thompson's collision detection article, valuable r1RightEdge is r1x + r1w.

float r1RightEdge = r1x + r1w;
if (r1RightEdge >= r2x) {
// right edge of r1 is past left edge of r2
}

Is valuable r1RightEdge vertical dot line of the blue rectangle in the picture? If so, why is the valuable r1RightEdge is r1x +r1w instead of r1x+r1h?

Kijimu7
  • 55
  • 8
  • 2
    You are confused by the word 'vertical line'. You need to learn more about coordinates. Think it this way: when you move on the plane in horizontal (left/right) direction you are changing the 'x' coordinate. When you move vertically (up/down) the 'y' is changing. To pass from the vertical right edge of the box, you have to move horizontally (x direction). If you move vertically, your distance to the right edge line will be fixed and you never reach to it. – S.Serpooshan Sep 24 '19 at 05:16
  • Thank you for the explanation! I understand now. – Kijimu7 Sep 24 '19 at 14:10

2 Answers2

1

Based on the example code

if (r1x + r1w >= r2x &&     // r1 right edge past r2 left
  r1x <= r2x + r2w &&       // r1 left edge past r2 right
  r1y + r1h >= r2y &&       // r1 top edge past r2 bottom
  r1y <= r2y + r2h) {       // r1 bottom edge past r2 top
    return true;
}
return false;

I under stand that x (in you case : r1x) mean horizontal position of the upper left dot of r1 - or R1LeftEdge, it only make sense if we add r1w (which is width) to it as they are both horizontal, the result is the horizontal upper right dot of r1 - or R1RightEdge. "r1x+r1h" doesn't make sense because one is horizontal and the other is vertical.

thienDX
  • 284
  • 2
  • 12
  • 1
    Your solution is too much specific. I believe, It works only for the kind of examples mentioned in the question. – v78 Sep 24 '19 at 07:03
  • 1
    It seem the thing that confuse OP is the variable naming, so i tried to explain what they mean. – thienDX Sep 24 '19 at 07:49
1

A generic and simpler solution can be:

// If one rectangle is on left side of other 
if (r1x > r2x + r2w || r2x > r1x + r1w) 
    return false; 

// If one rectangle is above other 
if (r1y > r2y + r2h || r2y > r1y + r1h) 
    return false; 

// If none of the above meet then there will be a intersection
return true;

This will also handle the special case when rectangles intersect but none of the corner of any rectangle lies inside other.

v78
  • 2,803
  • 21
  • 44