Created
February 20, 2021 20:49
-
-
Save gkmngrgn/9243e3d292f76ff3f104c28928ac17b0 to your computer and use it in GitHub Desktop.
collisions.lua
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- local functions like this one are only visible (you can only acces them) from the module (file). This is | |
-- a good practice to not pollute global namespace with things that are not supposed to be there. | |
-- This function just check if 2 rectangles collides and returns true or false. | |
local function checkCollision(a, b) | |
return a.x < b.x + b.w and | |
a.x + a.w > b.x and | |
a.y < b.y + b.h and | |
a.h + a.y > b.y | |
end | |
-- "move" tries to move "item" to position (new_x, new_y) | |
function mt:move(item, new_x, new_y) | |
-- First we store current position, we'll roll back if we encounter any obstacle. | |
local prev_x, prev_y = item.x, item.y | |
-- Let's be optimistic and assign the new values. | |
item.x, item.y = new_x, new_y | |
for _, other in ipairs(self.items) do | |
-- if any other item collides with moved one ("item") then let's just roll back to the position it was | |
-- before the function was called | |
if other ~= item and checkCollision(item, other) then | |
item.x, item.y = prev_x, prev_y | |
break -- "break" exits the loop imidiately | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment