Say I have two squares, both 10x10, with some small, unknown overlap.
Is there a way to draw the intersection of these two squares using the width, height and x,y coordinates of each square, while also not using an if statement?
Thanks.
Computer Graphics Stack Exchange is a question and answer site for computer graphics researchers and programmers. It only takes a minute to sign up.
Sign up to join this communitySay I have two squares, both 10x10, with some small, unknown overlap.
Is there a way to draw the intersection of these two squares using the width, height and x,y coordinates of each square, while also not using an if statement?
Thanks.
I'm assuming you want to calculate the bounds of the rectangle of intersection, so you can draw it later. As AlanWolfe mentioned, you will want to use the max and min functions. This is so you can retrieve the left-most, right-most, top and bottom squares. We'll call these placeholders right
, bottom
, left
, and top
(each of these will point to one of the two squares).
Now that you know these, you can start mathing. The top-left position of the intersection will be at (right.x_left, bottom.y_top)
. The bottom-right position of the intersection will be at (left.x_left + left.width, bottom.y_top + bottom.height)
.
To draw this rectangle (unconditionally), first you will need a location and a dimension, because most draw functions require these.
Intersection.width = Intersection.x_right - Intersection.x_left
and the same for the height. Now suppose the squares don't overlap. This would mean at least one dimension is negative. We don't want anything to draw in this case, so we will set any negative dimensions to zero.
Intersection.width = max(Intersection.width, 0)
and the same for the height. And to wrap up, we render our rectangle:
fillRect(Intersection.x_left, Intersection.y_top, Intersection.width, Intersection.height)
(right.x, bottom.y)
, which sound like points, not rectangles. Can you clarify? I'm not understanding how the top-left position is (right.x, bottom.y)
given what you've written above that.
$\endgroup$
Aug 5, 2017 at 4:05
top
, bottom
, left
, and right
are references; top
just references whatever one of the two is higher, and bottom
the lower one. left
references whatever one is to the left, and right
the one to the right. So, for instance, top
could be rectangle A, and right
could be rectangle A also. I'll edit the answer to clarify about the coordinates.
$\endgroup$