NeutronLoved/lib/rect.lua

76 lines
1.5 KiB
Lua
Raw Normal View History

2022-03-03 20:24:10 +01:00
rectgen = {}
function rectgen:new(x,y,w,h)
Rect = {x,y,w,h}
function Rect:move(x,y)
self[1] = self[1] + x
self[2] = self[2] + y
self:reAdapt()
end
function Rect:move_ip(x,y)
self[1] = x
self[2] = y
self:reAdapt()
end
function Rect:setSize(w,h)
self[3] = w
self[4] = h
self:reAdapt()
end
function Rect:move_center(x,y)
self[1] = x-self.w/2
self[2] = y-self.h/2
self:reAdapt()
end
function Rect:reAdapt()
self.x = self[1]
self.y = self[2]
self.w = self[3]
self.h = self[4]
self.center = {self.x+self.w/2,self.y+self.h/2}
self.center.x = self.x+self.w/2
self.center.y = self.y+self.h/2
self.up = self.y
self.left = self.x
self.right = self.x+self.w
self.down = self.y+self.h
end
function Rect:colliderect(orect,xoffset,yoffset,semisolid) -- AABB collision check
local result = true
local offx = xoffset or 0
local offy = yoffset or 0
if self.right+offx <= orect.left or self.left+offx>=orect.right then result = false end
if self.down+offy <= orect.up or self.up+offy>=orect.down then result = false end
if semi and result then
if not self.bottom<orect.top then result = false end
end
return result
end
function Rect:collidepoint(x,y)
return self.x<x and x<self.x+self.w and self.y<y and y<self.y+self.h
end
function Rect:colliderects(recttable,xoffset,yoffset,semisolid)
local result = {}
for i,v in pairs(recttable) do
if self:colliderect(v,xoffset,yoffset,semisolid) then table.insert(result,v) end
end
return result
end
Rect:reAdapt()
return Rect
end
return rectgen