PICO-8: Checking for Overlap
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
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
x2,y2 would be
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 (
b) that each have an
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
Save this file to your PICO-8 carts folder. Then load it by typing
load overlap in the command line mode of PICO-8.