Hi, guys. So I'm trying to get some faster collision detection going, but I think what I got is way too slow still.
--p = object 1 (size is 8px) --af = object 2 (size is 8px) check = true if(p.x + p.width < af.x) then check = false end if(p.x > af.x + af.width) then check = false end if(p.y + p.height < af.y) then check = false end if(p.y > af.y + af.height) then check = false end if(check) then --if our player is inside a after image if( p.x >= af.x and p.y >= af.y and p.x <= af.x + af.width and p.y <= af.y + af.height or p.x + p.width >= af.x and p.y >= af.y and p.x + p.width <= af.x + af.width and p.y <= af.y + af.height or p.x >= af.x and p.y + p.height >= af.y and p.x <= af.x + af.width and p.y + p.height <= af.y + af.height or p.x + p.width >= af.x and p.y + p.height >= af.y and p.x + p.width <= af.x + af.width and p.y + p.height <= af.y + af.height ) then --hit end end |
Can anyone help me simplify this code, and speed it up?
If I read your code correctly, you basically have two rectangles that either overlap or don't.
So, this is how I'd do it, given p and af as in your code:
-- get the intersection of p and af local l = max(p.x, af.x) local r = min(p.x+p.width, af.x+af.width) local t = max(p.y, af.y) local b = min(p.y+p.height, af.y+af.height) -- they overlapped if the area of intersection is greater than 0 if l < r and t < b then --hit end |
This code is just off of the top of my head, but a quick test in pico seems to work, so I think it's good.
Note it's generally more convenient to have rectangles in terms of l/r/t/b rather than x/w/y/h, to avoid the math I had to do there, but it's ultimately the same thing.
[Please log in to post a comment]