Checking for Overlap

This cart demonstrates one way to check for overlap between two boxes. There are many ways, but this is a simple way to do it in PICO-8. (Unlike other carts in this collection, the source code code for this cart is not intended to be used, but it just to display what you see when you run it.)

Notes: This method of checking for overlap actually checks to see if the two boxes are not overlapping. The example above is simplified into using x1,y1 and x2,y2 of each box. But in practice, you would usually just have an x,y and a w,h (width and height) to work with. In that case, x1,y1 would the same as x,y and x2,y2 would be x+w,y+h.

Turning This Into Code

If you want to turn this into a function for checking overlap, you just need to return true if all the conditions in the tutorial are false, but return false if any of the conditions are true.

Below is a verbose example function that assumes you have two boxes (a and b) that each have an x,y and w,h.

The second function is the same as the first, but it's condensed into one statement. It's not as easy to read, but it does the same thing.

function overlap(a,b)
 local test1 = a.x > (b.x + b.w)
 local test2 = a.y > (b.y + b.h)
 local test3 = (a.x + a.w) < b.x
 local test4 = (a.y + a.h) < b.y
 return not (test1 or test2 or test3 or test4)
end
--condensed version
function overlap(a,b)
 return not (a.x>b.x+b.w 
          or a.y>b.y+b.h 
          or a.x+a.w<b.x 
          or a.y+a.h<b.y)
end
Published Jun 25, 2017
StatusReleased
CategoryOther
PlatformsHTML5
Rating
(3)
AuthorMBoffin
GenreSimulation, Educational
Made withPICO-8
TagsPICO-8, sourcecode

Install instructions

Save this file to your PICO-8 carts folder. Then load it by typing load overlap in the command line mode of PICO-8.

Download

Download
overlap.p8.png 7 kB

Comments

Log in with itch.io to leave a comment.

(+1)

This is wonderful, thanks! The function both makes perfect sense _and_ does everything I want. I have put a thank you and a link to this cart in my code comments.

(+1)

This is super helpful!