I found an older demo I wrote a while back - it works, sort of. I found it only worked so well because the player and the singular tile I used to test collisions had the same dimensions. I'm not sure whether it also worked because I wasn't drawing to a canvas and/or I wasn't trying to flip the player's sprite by negating the scale. When I tried to change the width and height of the player in the demo by changing its sprite, the player would clip into the tile and slip over it... you can see it for yourself, I attached it below. Here is the code I used to respond to the collision in the demo:
Code: Select all
-- s1 would be the player
-- s2 would be the test tile
-- yspd is the player's y velocity
function resolveSides(s1, s2)
if AABB(s1.x,s1.y,s1.w,s1.h, s2.x,s2.y,s2.w,s2.h) then
-- TOP:
if (s1.x + s1.w > s2.x or s1.x < s2.x + s2.w) and (s1.y + s1.h > s2.y and s1.y + s1.h < s2.y + s2.h/2) and s1.yspd > 0 then
s1.yspd = 0
s1.y = s2.y - s1.h
-- BOTTOM:
elseif (s1.x + s1.w > s2.x + 5 and s1.x < s2.x + s2.w - 5) and (s1.y < s2.y + s2.h and s1.y > s2.y + s2.h/2) then
s1.yspd = 0
s1.y = s2.y + s1.h
-- RIGHT:
elseif (s1.y + s1.h > s2.y or s1.y < s2.y + s2.h) and (s1.x + s1.w > s2.x and s1.x + s1.h < s2.x + s2.w/2) then
s1.x = s2.x - s1.w
-- LEFT:
elseif (s1.y + s1.h > s2.y or s1.y < s2.y + s2.h) and (s1.x < s2.x + s2.w and s1.x > s2.x + s2.w/2) then
s1.x = s2.x + s1.w
end
end
end