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
StatusReleased
CategoryOther
PlatformsHTML5
Rating
Rated 5.0 out of 5 stars
(10 total ratings)
AuthorMBoffin (Dylan Bennett)
GenreSimulation, Educational
Made withPICO-8
TagsPICO-8, sourcecode

Download

Download
overlap.p8.png 7 kB

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.

Comments

Log in with itch.io to leave a comment.

This just helped me out SO much, thx a lot!

(+1)

THANKS A LOT! this saved me a lot of frustration :P

(+1)

Thanks for this! One note for anyone who sees this code in the future: with this code, an 8x8 sprite has a width/height of 7. If you want to treat the width/height as 8, subtract 1 from the width and height in each of the lines above when comparing

(+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!