bytepath/obj/Area.lua

79 lines
2 KiB
Lua

---@module 'obj/Area'
---@class Area:Object
---@field room Room
---@field game_objects GameObject[]
---@field world table|nil
local Area = Object:extend()
---Instantiates area
function Area:new(room)
self.room = room
self.game_objects = {}
self.world = nil
self.timer = Timer()
end
---Updates area
---@param dt number
function Area:update(dt)
for i = #self.game_objects, 1, -1 do
local game_object = self.game_objects[i]
game_object:update(dt)
if game_object:isDead() then
table.remove(self.game_objects, i)
end
end
self.timer:update(dt)
end
---Draws area
function Area:draw()
for _, game_object in ipairs(self.game_objects) do game_object:draw() end
end
---Destroys area
function Area:destroy()
if self.timer then
self.timer:clear() -- cancel all tweens/after/every
self.timer = nil
end
for i = #self.game_objects, 1, -1 do
local game_object = self.game_objects[i]
game_object:kill()
table.remove(self.game_objects, i)
end
self.game_objects = {}
if self.world then self.world = nil end
end
---Adds game object to area
---@param game_object_type string name of game object's class
---@param x number|nil horizontal position
---@param y number|nil vertical position
---@param opts table|nil additional arguments
---@return GameObject
function Area:addGameObject(game_object_type, x, y, opts)
local game_object = _G[game_object_type](self, x or 0, y or 0, opts or {})
table.insert(self.game_objects, game_object)
return game_object
end
---Initializes HC collision manager as a world
---@param cell_size number|nil
function Area:addCollisionManager(cell_size)
self.world = HC(cell_size or 100)
end
---Slows down gameplay
---@param amount number percentage to which game will slow down
---@param duration number duration in seconds of slow down
function Area:slow(amount, duration)
slow_amnt = amount
self.timer:tween(duration, _G, {slow_amnt = 1}, 'in-out-cubic')
end
return Area