Mothback/code/collision.lua
2022-03-16 21:01:04 -04:00

94 lines
2.0 KiB
Lua

Collision = class()
LoadedObjects.Collisions = {}
LoadedObjects.Platforms = {}
LoadedObjects.Ladders = {}
LoadedObjects.Hazards = {}
LoadedObjects.Rooms = {}
--[[
Collision
[bool flag] is_disabled
> if true used for collision
[bool flag] is_colliding
> if true, this collision is colliding
[vec2 position] from - x, y
> top right corner of collision box
[vec2 position] to - x, y
> bottom left corner of collision box
[int property] width
> width of collision box
[int property] height
> height of collision box
--]]
-- can also be called with only ox and oy, where they become the width and height instead
function Collision:new(ox,oy,tx,ty)
local o = {is_colliding = false, is_disabled = false}
if tx ~= nil and ty ~= nil then
o.from = {x = ox, y = oy}
o.to = {x = tx, y = ty}
o.width = o.to.x - o.from.x
o.height = o.to.y - o.from.y
else
o.width = ox
o.height = oy
o.from = {x = 0, y = 0}
o.to = {x = 0, y = 0}
end
setmetatable(o, self)
return o
end
function Collision:centerAt(x, y)
self.from.x = x-self.width/2
self.from.y = y-self.height/2
self.to.x = x+self.width/2
self.to.y = y+self.height/2
end
function Collision:placeAt(x, y)
self.from.x = x or self.from.x
self.from.y = y or self.from.y
self.to.x = self.from.x + self.width
self.to.y = self.from.x + self.height
end
function Collision:containsPoint(x, y)
return x >= self.from.x and
y >= self.from.y and
x <= self.to.x and
y <= self.to.y
end
function Collision:draw(color)
if self.is_colliding == true then
love.graphics.setColor(0,1,0,0.5)
elseif color == 1 then
love.graphics.setColor(1,0,0,0.5)
elseif color == 2 then
love.graphics.setColor(0,1,1,0.5)
end
love.graphics.rectangle("fill",self.from.x-Camera.pos.x, self.from.y-Camera.pos.y, self.width, self.height)
love.graphics.setColor(0,1,90,0.5)
love.graphics.rectangle("line",self.from.x-Camera.pos.x, self.from.y-Camera.pos.y, self.width, self.height)
end
function Collision:asRect()
return Rect:fromCoords(self.from.x, self.from.y, self.to.x, self.to.y)
end