Hello so I am making a game where you eat smaller fish to grow larger to eat bigger fish and so I need a way for the player to collide with fish. I tried to make myself a collision function but it doesn't work. Can someone show me a rectangle collision function?
My collision function:
function player:collidiesWith(other)
if not other.rect then
other.rect = makeRect(other)
end
local lMost, rMost, bMost, tMost
if self.rect.left < other.rect.left then
lMost = self.rect
rMost = other.rect
else
lMost = other.rect
rMost = self.rect
end
if self.rect.top < other.rect.top then
tMost = self.rect
bMost = other.rect
else
tMost = other.rect
bMost = self.rect
end
local xdist = rMost.left - lMost.right
local ydist = bMost.top - tMost.bottom
return xdist <= 0 and ydist <= 0
end
I've written a rectangular collision detection for your game and added the width/height of player and fishes to their tables to make calculation easier.
function player:collidiesWith(other)
if other.x+other.width>self.x and other.x<self.x+self.width and other.y+other.height>self.y and other.y<self.y+self.height then return true
else return false end
end
Other changes are in entities:spawn(), entities:load(), entities:checkCollision() and player:load().
Use diff to find them
Another hint: you use a similar table.insert in both entities:spawn() and entities:load(). You should avoid any duplication of code, maybe make a function for the insert?