lovexp/asteroids/actors.lua
2025-11-20 21:37:13 -05:00

125 lines
3.3 KiB
Lua

local love = require("love")
local phys = require("phys")
local inspect = require("inspect")
local actors = {}
function actors.buildActors(game)
local asteroids = {}
local asteroids_mt = { __index = asteroids }
function asteroids.new(asteroid)
local stageIndex = asteroid.stage or #game.asteroids.stages
local stage = game.asteroids.stages[stageIndex]
local instance = {
angle = math.random() * phys.tau,
speed = stage.speed,
facing = math.random() * phys.tau,
spin = (math.random() - 0.5),
radius = stage.radius,
sprite = stage.sprite,
}
for k, v in pairs(asteroid) do
instance[k] = v
end
instance.stage = stageIndex
setmetatable(instance, asteroids_mt)
return instance
end
function asteroids:draw()
local width = self.sprite:getWidth()
local height = self.sprite:getHeight()
love.graphics.push()
love.graphics.setColor(1, 1, 1)
local scale = 2 * self.radius / math.max(width, height)
love.graphics.draw(self.sprite,
self.x,
self.y,
self.facing,
scale,
scale,
width / 2,
height / 2
)
love.graphics.pop()
end
local bullets = {}
local bullets_mt = { __index = bullets }
function bullets.new(bullet)
local instance = {
spin = 0,
}
for k, v in pairs(game.ship.bullet) do
instance[k] = v
end
for k, v in pairs(bullet) do
instance[k] = v
end
instance.sound = love.audio.newSource(game.ship.bullet.sound)
instance.timeLeft = instance.time
setmetatable(instance, bullets_mt)
return instance
end
function bullets:draw()
love.graphics.push()
love.graphics.setColor(0, 1, 0)
love.graphics.circle('fill', self.x, self.y, self.radius)
love.graphics.pop()
end
local ships = {}
local ships_mt = { __index = ships }
function ships.new(ship)
local instance = {
x = game.width / 2,
y = game.height / 2,
angle = 0,
speed = 0,
spin = 0,
facing = phys.tau * 3 / 4,
radius = game.ship.radius,
}
for k, v in pairs(game.ship) do
instance[k] = v
end
for k, v in pairs(ship) do
instance[k] = v
end
setmetatable(instance, ships_mt)
return instance
end
function ships:draw()
love.graphics.push()
love.graphics.translate(self.x, self.y)
love.graphics.setColor(1, 1, 1)
local width = self.sprite:getWidth()
local height = self.sprite:getHeight()
local scale = 2 * game.ship.radius / math.max(width, height)
love.graphics.draw(game.ship.sprite,
0,
0,
(self.facing + phys.tau / 4) % phys.tau,
scale,
scale,
width / 2,
height / 2
)
-- TODO rocket exhaust
love.graphics.pop()
end
return {
asteroids = asteroids,
bullets = bullets,
ships = ships,
}
end
return actors