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?
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 community
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
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)