Compare commits

...

25 commits

Author SHA1 Message Date
bceb46a612 hot pink bullets 2025-11-21 23:37:05 -05:00
c1bf95005e add rocket plume particle sprite 2025-11-21 23:34:14 -05:00
e8e4ba9d04 better rocket plume 2025-11-21 22:32:03 -05:00
e8363338c8 throttle governed rocket plume 2025-11-20 23:28:48 -05:00
e2f02985d3 constant rocket plume 2025-11-20 22:53:33 -05:00
7eee00d7ea add engine burn 2025-11-20 22:07:03 -05:00
e2fe2499d4 add throttle 2025-11-20 21:42:14 -05:00
38af0bcaa1 add ship actor 2025-11-20 21:37:13 -05:00
583efe528c add bullet actor 2025-11-20 21:26:44 -05:00
c1c774338e reduce asteroid init 2025-11-20 21:07:12 -05:00
b2b70ee910 extract asteroids ctor 2025-11-20 20:58:15 -05:00
21c432f583 explore graphics stack 2025-11-20 20:12:23 -05:00
63b296e19c spinning asteroids 2025-11-17 23:15:21 -05:00
eae3659768 asteroid sprites, spins and facing for all actors 2025-11-17 23:10:15 -05:00
13bec1a0aa apply ship velocity to bullets 2025-11-17 20:44:11 -05:00
5bcf22a6f8 bullet recoil, use tau 2025-11-17 20:31:14 -05:00
f5df911707 fix atan issue
the love2d that I'm using doesn't have the new atan arity lol
2025-11-17 20:21:42 -05:00
9cdf032c39 add phys.apply 2025-11-16 22:51:51 -05:00
fddb06ed8b extract phys 2025-11-16 12:06:35 -05:00
b832731fa0 introduce actor trait 2025-11-15 21:43:10 -05:00
11a4fe9826 bullet recoil 2025-11-15 20:54:47 -05:00
ba00a4b8dd bullet sound 2025-11-15 20:46:59 -05:00
d498c7c78a ship sprite 2025-11-15 20:32:13 -05:00
1b1ed94b2f gamepad fire 2025-11-15 16:42:02 -05:00
18062e9ca1 gamepad turn 2025-11-15 16:29:07 -05:00
21 changed files with 4164 additions and 77 deletions

1
asteroids/.gitignore vendored Normal file
View file

@ -0,0 +1 @@
tmp

158
asteroids/actors.lua Normal file
View file

@ -0,0 +1,158 @@
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(1, 0.16, 1)
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,
throttle = 0,
}
for k, v in pairs(game.ship) do
instance[k] = v
end
for k, v in pairs(ship) do
instance[k] = v
end
instance.engineSound = love.audio.newSource(instance.engineSound)
instance.engineSound:setVolume(0)
instance.engineSound:setLooping(true)
instance.rocketPlume = love.graphics.newParticleSystem(instance.rocketPlume)
instance.rocketPlume:setColors(
0.37, 0.65, 1.00, 0.8,
0.45, 0.65, 0.9, 0.8,
0.5, 0.6, 0.85, 0.8
)
instance.rocketPlume:setSizes(1.0, 0.9, 0.1)
instance.rocketPlume:setEmissionRate(1000)
-- TODO probably governed most by thrust
instance.rocketPlume:setParticleLifetime(0.1, 0.25)
instance.rocketPlume:setEmissionArea('normal', 1.5, 1.5)
instance.rocketPlume:setSpeed(150, 300)
instance.rocketPlume:setRadialAcceleration(40, 80)
instance.rocketPlume:setLinearDamping(0, 0)
instance.rocketPlume:setDirection(phys.tau * 3 / 4)
instance.rocketPlume:setSpread(0)
instance.rocketPlume:setSizeVariation(0)
instance.rocketPlume:setSpin(0.5, 1)
instance.rocketPlume:setTangentialAcceleration(0, 0)
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
)
self.rocketPlume:setEmissionRate(1000 * self.throttle)
love.graphics.draw(self.rocketPlume,
0,
0,
(self.facing + phys.tau * 3 / 4) % phys.tau,
scale,
scale,
0,
height * 0.6
)
love.graphics.pop()
end
return {
asteroids = asteroids,
bullets = bullets,
ships = ships,
}
end
return actors

371
asteroids/inspect.lua Normal file
View file

@ -0,0 +1,371 @@
local _tl_compat; if (tonumber((_VERSION or ''):match('[%d.]*$')) or 0) < 5.3 then local p, m = pcall(require, 'compat53.module'); if p then _tl_compat = m end end; local math = _tl_compat and _tl_compat.math or math; local string = _tl_compat and _tl_compat.string or string; local table = _tl_compat and _tl_compat.table or table; local type = type
local inspect = { Options = {} }
inspect._VERSION = 'inspect.lua 3.1.0'
inspect._URL = 'http://github.com/kikito/inspect.lua'
inspect._DESCRIPTION = 'human-readable representations of tables'
inspect._LICENSE = [[
MIT LICENSE
Copyright (c) 2022 Enrique García Cota
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
]]
inspect.KEY = setmetatable({}, { __tostring = function() return 'inspect.KEY' end })
inspect.METATABLE = setmetatable({}, { __tostring = function() return 'inspect.METATABLE' end })
local tostring = tostring
local rep = string.rep
local match = string.match
local char = string.char
local gsub = string.gsub
local fmt = string.format
local _rawget
if rawget then
_rawget = rawget
else
_rawget = function(t, k) return t[k] end
end
local function rawpairs(t)
return next, t, nil
end
local function smartQuote(str)
if match(str, '"') and not match(str, "'") then
return "'" .. str .. "'"
end
return '"' .. gsub(str, '"', '\\"') .. '"'
end
local shortControlCharEscapes = {
["\a"] = "\\a", ["\b"] = "\\b", ["\f"] = "\\f", ["\n"] = "\\n",
["\r"] = "\\r", ["\t"] = "\\t", ["\v"] = "\\v", ["\127"] = "\\127",
}
local longControlCharEscapes = { ["\127"] = "\127" }
for i = 0, 31 do
local ch = char(i)
if not shortControlCharEscapes[ch] then
shortControlCharEscapes[ch] = "\\" .. i
longControlCharEscapes[ch] = fmt("\\%03d", i)
end
end
local function escape(str)
return (gsub(gsub(gsub(str, "\\", "\\\\"),
"(%c)%f[0-9]", longControlCharEscapes),
"%c", shortControlCharEscapes))
end
local luaKeywords = {
['and'] = true,
['break'] = true,
['do'] = true,
['else'] = true,
['elseif'] = true,
['end'] = true,
['false'] = true,
['for'] = true,
['function'] = true,
['goto'] = true,
['if'] = true,
['in'] = true,
['local'] = true,
['nil'] = true,
['not'] = true,
['or'] = true,
['repeat'] = true,
['return'] = true,
['then'] = true,
['true'] = true,
['until'] = true,
['while'] = true,
}
local function isIdentifier(str)
return type(str) == "string" and
not not str:match("^[_%a][_%a%d]*$") and
not luaKeywords[str]
end
local flr = math.floor
local function isSequenceKey(k, sequenceLength)
return type(k) == "number" and
flr(k) == k and
1 <= (k) and
k <= sequenceLength
end
local defaultTypeOrders = {
['number'] = 1, ['boolean'] = 2, ['string'] = 3, ['table'] = 4,
['function'] = 5, ['userdata'] = 6, ['thread'] = 7,
}
local function sortKeys(a, b)
local ta, tb = type(a), type(b)
if ta == tb and (ta == 'string' or ta == 'number') then
return (a) < (b)
end
local dta = defaultTypeOrders[ta] or 100
local dtb = defaultTypeOrders[tb] or 100
return dta == dtb and ta < tb or dta < dtb
end
local function getKeys(t)
local seqLen = 1
while _rawget(t, seqLen) ~= nil do
seqLen = seqLen + 1
end
seqLen = seqLen - 1
local keys, keysLen = {}, 0
for k in rawpairs(t) do
if not isSequenceKey(k, seqLen) then
keysLen = keysLen + 1
keys[keysLen] = k
end
end
table.sort(keys, sortKeys)
return keys, keysLen, seqLen
end
local function countCycles(x, cycles)
if type(x) == "table" then
if cycles[x] then
cycles[x] = cycles[x] + 1
else
cycles[x] = 1
for k, v in rawpairs(x) do
countCycles(k, cycles)
countCycles(v, cycles)
end
countCycles(getmetatable(x), cycles)
end
end
end
local function makePath(path, a, b)
local newPath = {}
local len = #path
for i = 1, len do newPath[i] = path[i] end
newPath[len + 1] = a
newPath[len + 2] = b
return newPath
end
local function processRecursive(process,
item,
path,
visited)
if item == nil then return nil end
if visited[item] then return visited[item] end
local processed = process(item, path)
if type(processed) == "table" then
local processedCopy = {}
visited[item] = processedCopy
local processedKey
for k, v in rawpairs(processed) do
processedKey = processRecursive(process, k, makePath(path, k, inspect.KEY), visited)
if processedKey ~= nil then
processedCopy[processedKey] = processRecursive(process, v, makePath(path, processedKey), visited)
end
end
local mt = processRecursive(process, getmetatable(processed), makePath(path, inspect.METATABLE), visited)
if type(mt) ~= 'table' then mt = nil end
setmetatable(processedCopy, mt)
processed = processedCopy
end
return processed
end
local function puts(buf, str)
buf.n = buf.n + 1
buf[buf.n] = str
end
local Inspector = {}
local Inspector_mt = { __index = Inspector }
local function tabify(inspector)
puts(inspector.buf, inspector.newline .. rep(inspector.indent, inspector.level))
end
function Inspector:getId(v)
local id = self.ids[v]
local ids = self.ids
if not id then
local tv = type(v)
id = (ids[tv] or 0) + 1
ids[v], ids[tv] = id, id
end
return tostring(id)
end
function Inspector:putValue(v)
local buf = self.buf
local tv = type(v)
if tv == 'string' then
puts(buf, smartQuote(escape(v)))
elseif tv == 'number' or tv == 'boolean' or tv == 'nil' or
tv == 'cdata' or tv == 'ctype' then
puts(buf, tostring(v))
elseif tv == 'table' and not self.ids[v] then
local t = v
if t == inspect.KEY or t == inspect.METATABLE then
puts(buf, tostring(t))
elseif self.level >= self.depth then
puts(buf, '{...}')
else
if self.cycles[t] > 1 then puts(buf, fmt('<%d>', self:getId(t))) end
local keys, keysLen, seqLen = getKeys(t)
puts(buf, '{')
self.level = self.level + 1
for i = 1, seqLen + keysLen do
if i > 1 then puts(buf, ',') end
if i <= seqLen then
puts(buf, ' ')
self:putValue(t[i])
else
local k = keys[i - seqLen]
tabify(self)
if isIdentifier(k) then
puts(buf, k)
else
puts(buf, "[")
self:putValue(k)
puts(buf, "]")
end
puts(buf, ' = ')
self:putValue(t[k])
end
end
local mt = getmetatable(t)
if type(mt) == 'table' then
if seqLen + keysLen > 0 then puts(buf, ',') end
tabify(self)
puts(buf, '<metatable> = ')
self:putValue(mt)
end
self.level = self.level - 1
if keysLen > 0 or type(mt) == 'table' then
tabify(self)
elseif seqLen > 0 then
puts(buf, ' ')
end
puts(buf, '}')
end
else
puts(buf, fmt('<%s %d>', tv, self:getId(v)))
end
end
function inspect.inspect(root, options)
options = options or {}
local depth = options.depth or (math.huge)
local newline = options.newline or '\n'
local indent = options.indent or ' '
local process = options.process
if process then
root = processRecursive(process, root, {}, {})
end
local cycles = {}
countCycles(root, cycles)
local inspector = setmetatable({
buf = { n = 0 },
ids = {},
cycles = cycles,
depth = depth,
level = 0,
newline = newline,
indent = indent,
}, Inspector_mt)
inspector:putValue(root)
return table.concat(inspector.buf)
end
setmetatable(inspect, {
__call = function(_, root, options)
return inspect.inspect(root, options)
end,
})
return inspect

3453
asteroids/luaunit.lua Normal file

File diff suppressed because it is too large Load diff

View file

@ -1,4 +1,7 @@
local love = require("love")
local phys = require("phys")
local inspect = require("inspect")
local actors = require("actors")
local function initGame()
return {
@ -7,32 +10,39 @@ local function initGame()
ship = {
radius = 30,
bullet = {
timerLimit = 0.5,
radius = 5,
recoil = 10,
speed = 500,
time = 4,
sound = love.sound.newSoundData('resources/bullet.mp3'),
},
sprite = love.graphics.newImage('resources/playerShip1_blue.png'),
maxThrust = 200,
engineSound = love.sound.newSoundData('resources/enginehum3.ogg'),
rocketPlume = love.graphics.newImage('resources/sparkle_cloud.png'),
},
asteroids = {
stages = {
{ speed = 120, radius = 15 },
{ speed = 70, radius = 30 },
{ speed = 50, radius = 50 },
{ speed = 20, radius = 80 },
{ speed = 120, radius = 15, sprite = love.graphics.newImage('resources/meteorBrown_tiny1.png') },
{ speed = 70, radius = 30, sprite = love.graphics.newImage('resources/meteorBrown_small1.png') },
{ speed = 50, radius = 50, sprite = love.graphics.newImage('resources/meteorBrown_med1.png') },
{ speed = 20, radius = 80, sprite = love.graphics.newImage('resources/meteorBrown_big1.png') },
},
},
controls = {
ship = {
turnRate = 10,
maxThrust = 200,
},
},
}
end
-- The constant properties of the game.
local game = initGame()
local function initState()
---@diagnostic disable-next-line: redefined-local
local actors = actors.buildActors(game)
local asteroids = {
{
x = 100,
@ -47,26 +57,17 @@ local function initState()
y = game.height - 100,
}
}
for _, asteroid in ipairs(asteroids) do
asteroid.angle = love.math.random() * (2 * math.pi)
asteroid.stage = #game.asteroids.stages
for i, template in ipairs(asteroids) do
asteroids[i] = actors.asteroids.new(template)
end
local joystick = nil
if love.joystick.getJoystickCount() == 1 then
joystick = love.joystick.getJoysticks()[1]
end
return {
ship = {
x = game.width / 2,
y = game.height / 2,
angle = 0,
speed = {
x = 0,
y = 0,
}
},
-- the time after which the ship can fire another bullet
bulletTimer = game.ship.bullet.timerLimit,
debug = true,
actors = actors,
ship = actors.ships.new({}),
bullets = {},
asteroids = asteroids,
controls = {
@ -75,9 +76,16 @@ local function initState()
}
end
-- The varying properties of a game being played.
local state = {}
local function reset()
if state.ship then
state.ship.engineSound:stop()
for _, bullet in ipairs(state.bullets) do
bullet.sound:stop()
end
end
state = initState()
end
@ -85,26 +93,37 @@ function love.load()
reset()
end
-- updates the actor's location by applying the passage of time within the game world
local function update(actor, dt)
phys.update(actor, dt)
actor.x = actor.x % game.width
actor.y = actor.y % game.height
end
function love.update(dt)
if love.keyboard.isDown('right') then
state.ship.angle = state.ship.angle + game.controls.ship.turnRate * dt
end
if love.keyboard.isDown('left') then
state.ship.angle = state.ship.angle - game.controls.ship.turnRate * dt
end
state.ship.angle = state.ship.angle % (2 * math.pi)
state.ship.rocketPlume:update(dt)
if state.controls.joystick ~= nil then
local thrust = state.controls.joystick:getGamepadAxis('triggerright') * game.controls.ship.maxThrust
state.ship.speed.x = state.ship.speed.x + math.cos(state.ship.angle) * thrust * dt
state.ship.speed.y = state.ship.speed.y + math.sin(state.ship.angle) * thrust * dt
end
state.ship.x = (state.ship.x + state.ship.speed.x * dt) % game.width
state.ship.y = (state.ship.y + state.ship.speed.y * dt) % game.height
state.ship.throttle = state.controls.joystick:getGamepadAxis('triggerright')
if state.ship.throttle > 0 then
local speed = state.ship.throttle * state.ship.maxThrust * dt
phys.apply(state.ship, { speed = speed, angle = state.ship.facing })
if not state.ship.engineSound:isPlaying() then
state.ship.engineSound:play()
end
end
state.ship.engineSound:setVolume(state.ship.throttle * 0.5)
-- TODO which is better, keeping the sound playing looping at 0 or checking the
-- state each update?
if state.ship.throttle == 0 then
if state.ship.engineSound:isPlaying() then
state.ship.engineSound:stop()
end
end
local function areCirclesIntersecting(aX, aY, aRadius, bX, bY, bRadius)
return (aX - bX) ^ 2 + (aY - bY) ^ 2 <= (aRadius + bRadius) ^ 2
local spin = state.controls.joystick:getGamepadAxis('leftx') * game.controls.ship.turnRate
state.ship.facing = (state.ship.facing + spin * dt)
end
update(state.ship, dt)
for bulletIndex = #state.bullets, 1, -1 do
local bullet = state.bullets[bulletIndex]
@ -112,28 +131,27 @@ function love.update(dt)
if bullet.timeLeft <= 0 then
table.remove(state.bullets, bulletIndex)
else
bullet.x = (bullet.x + math.cos(bullet.angle) * game.ship.bullet.speed * dt) % game.width
bullet.y = (bullet.y + math.sin(bullet.angle) * game.ship.bullet.speed * dt) % game.height
update(bullet, dt)
end
for asteroidIndex = #state.asteroids, 1, -1 do
local asteroid = state.asteroids[asteroidIndex]
if areCirclesIntersecting(bullet.x, bullet.y, game.ship.bullet.radius, asteroid.x, asteroid.y, game.asteroids.stages[asteroid.stage].radius) then
if phys.intersects(bullet, asteroid) then
table.remove(state.bullets, bulletIndex)
if asteroid.stage > 1 then
local angle1 = love.math.random() * (2 * math.pi)
local angle2 = (angle1 - math.pi) % (2 * math.pi)
table.insert(state.asteroids, {
local angle1 = love.math.random() * phys.tau
local angle2 = angle1 - phys.tau / 2
table.insert(state.asteroids, state.actors.asteroids.new({
x = asteroid.x,
y = asteroid.y,
angle = angle1,
stage = asteroid.stage - 1,
})
table.insert(state.asteroids, {
}))
table.insert(state.asteroids, state.actors.asteroids.new({
x = asteroid.x,
y = asteroid.y,
angle = angle2,
stage = asteroid.stage - 1,
})
}))
end
table.remove(state.asteroids, asteroidIndex)
break
@ -141,26 +159,10 @@ function love.update(dt)
end
end
state.bulletTimer = state.bulletTimer + dt
if love.keyboard.isDown('s') then
if state.bulletTimer >= game.ship.bullet.timerLimit then
state.bulletTimer = 0
table.insert(state.bullets, {
x = state.ship.x + math.cos(state.ship.angle) * game.ship.radius,
y = state.ship.y + math.sin(state.ship.angle) * game.ship.radius,
angle = state.ship.angle,
timeLeft = game.ship.bullet.time,
})
end
end
for _, asteroid in ipairs(state.asteroids) do
asteroid.x = (asteroid.x + math.cos(asteroid.angle) * game.asteroids.stages[asteroid.stage].speed * dt) %
game.width
asteroid.y = (asteroid.y + math.sin(asteroid.angle) * game.asteroids.stages[asteroid.stage].speed * dt) %
game.height
update(asteroid, dt)
if areCirclesIntersecting(state.ship.x, state.ship.y, game.ship.radius, asteroid.x, asteroid.y, game.asteroids.stages[asteroid.stage].radius) then
if phys.intersects(state.ship, asteroid) then
reset()
break
end
@ -171,30 +173,47 @@ function love.update(dt)
end
end
function love.gamepadpressed(joystick, button)
if joystick ~= state.controls.joystick then
return
end
if button == "b" then
-- debounce, perhaps
local bullet = state.actors.bullets.new({
x = state.ship.x + math.cos(state.ship.facing) * game.ship.radius,
y = state.ship.y + math.sin(state.ship.facing) * game.ship.radius,
angle = state.ship.facing,
facing = state.ship.facing,
})
phys.apply(bullet, state.ship)
table.insert(state.bullets, bullet)
bullet.sound:play()
phys.apply(state.ship, { speed = game.ship.bullet.recoil, angle = state.ship.facing + phys.tau / 2 })
end
if button == "x" then
print(inspect(state.ship))
end
end
function love.draw()
if state.debug then
love.graphics.setColor(1, 1, 1)
love.graphics.line(game.width / 2, 0, game.width / 2, game.height)
love.graphics.line(0, game.height / 2, game.width, game.height / 2)
end
for y = -1, 1 do
for x = -1, 1 do
love.graphics.origin()
love.graphics.translate(x * game.width, y * game.height)
love.graphics.setColor(0, 0, 1)
love.graphics.circle('fill', state.ship.x, state.ship.y, game.ship.radius)
local shipCircleDistance = game.ship.radius * 2 / 3
love.graphics.setColor(0, 1, 1)
love.graphics.circle(
'fill',
state.ship.x + math.cos(state.ship.angle) * shipCircleDistance,
state.ship.y + math.sin(state.ship.angle) * shipCircleDistance,
game.ship.radius / 6
)
state.ship:draw()
for _, bullet in ipairs(state.bullets) do
love.graphics.setColor(0, 1, 0)
love.graphics.circle('fill', bullet.x, bullet.y, game.ship.bullet.radius)
bullet:draw()
end
for _, asteroid in ipairs(state.asteroids) do
love.graphics.setColor(1, 1, 0)
love.graphics.circle('fill', asteroid.x, asteroid.y, game.asteroids.stages[asteroid.stage].radius)
asteroid:draw()
end
end
end

36
asteroids/phys.lua Normal file
View file

@ -0,0 +1,36 @@
local inspect = require('inspect')
local phys = {
tau = 2 * math.pi
}
-- returns true if the two actors intersect
function phys.intersects(actor1, actor2)
return (actor1.x - actor2.x) ^ 2 + (actor1.y - actor2.y) ^ 2 <= (actor1.radius + actor2.radius) ^ 2
end
-- updates the actor's location by applying the passage of time
function phys.update(actor, dt)
assert(actor.speed >= 0)
local dv = actor.speed * dt
actor.x = actor.x + math.cos(actor.angle) * dv
actor.y = actor.y + math.sin(actor.angle) * dv
local dr = actor.spin * dt
actor.facing = (actor.facing + dr) % phys.tau
end
function phys.apply(actor, force)
local ax = math.cos(actor.angle) * actor.speed
local ay = math.sin(actor.angle) * actor.speed
local fx = math.cos(force.angle) * force.speed
local fy = math.sin(force.angle) * force.speed
local x = ax + fx
local y = ay + fy
local speed = math.sqrt(x ^ 2 + y ^ 2)
local angle = math.atan2(y, x)
actor.speed = speed
actor.angle = angle
end
return phys

Binary file not shown.

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 982 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 881 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 692 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 667 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 461 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 371 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 739 B

49
asteroids/test_phys.lua Normal file
View file

@ -0,0 +1,49 @@
t = require('luaunit')
local phys = require('phys')
function TestUpdate()
local actor = { x = 0, y = 0, speed = 1, angle = math.pi }
phys.update(actor, 0.1)
t.assertAlmostEquals(
actor,
{ x = -0.1, y = 0, speed = 1, angle = math.pi })
end
function TestApply()
local actor = { x = 0, y = 0, speed = 1, angle = math.pi }
phys.apply(actor, { speed = 1, angle = 0 })
t.assertAlmostEquals(
{ x = actor.x, y = actor.y, speed = actor.speed },
{ x = 0, y = 0, speed = 0 })
phys.apply(actor, { speed = 1, angle = math.pi })
t.assertAlmostEquals(
actor,
{ x = 0, y = 0, speed = 1, angle = math.pi }
)
phys.apply(actor, { speed = 1, angle = math.pi / 2 })
t.assertAlmostEquals(
actor,
{ x = 0, y = 0, speed = math.sqrt(2), angle = math.pi * 3 / 4 })
actor = { x = 0, y = 0, speed = 0, angle = 0 }
phys.apply(actor, { speed = 1, angle = math.pi / 2 })
t.assertAlmostEquals(
actor,
{ x = 0, y = 0, speed = 1, angle = math.pi / 2 })
phys.apply(actor, { speed = 1, angle = math.pi / 2 })
t.assertAlmostEquals(
actor,
{ x = 0, y = 0, speed = 2, angle = math.pi / 2 })
phys.apply(actor, { speed = 1, angle = math.pi })
t.assertAlmostEquals(
actor,
{ x = 0, y = 0, speed = 0, angle = 0 }
)
end
os.exit(t.LuaUnit.run())