diff --git a/asteroids/main.lua b/asteroids/main.lua index a0ad3ee..0bc5df9 100644 --- a/asteroids/main.lua +++ b/asteroids/main.lua @@ -1,4 +1,5 @@ local love = require("love") +local phys = require("phys") local function initGame() return { @@ -68,7 +69,8 @@ local function initState() speed = { x = 0, y = 0, - } + }, + radius = game.ship.radius, }, bullets = {}, asteroids = asteroids, @@ -88,17 +90,11 @@ function love.load() reset() end --- updates the actor's location by applying the passage of time --- TODO ship --- TODO spin +-- updates the actor's location by applying the passage of time within the game world local function update(actor, dt) - local dv = actor.speed * dt - actor.x = (actor.x + math.cos(actor.angle) * dv) % game.width - actor.y = (actor.y + math.sin(actor.angle) * dv) % game.height -end - -local function intersects(actor1, actor2) - return (actor1.x - actor2.x) ^ 2 + (actor1.y - actor2.y) ^ 2 <= (actor1.radius + actor2.radius) ^ 2 + phys.update(actor, dt) + actor.x = actor.x % game.width + actor.y = actor.y % game.height end function love.update(dt) @@ -113,10 +109,6 @@ function love.update(dt) 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 - local function areCirclesIntersecting(aX, aY, aRadius, bX, bY, bRadius) - return (aX - bX) ^ 2 + (aY - bY) ^ 2 <= (aRadius + bRadius) ^ 2 - end - for bulletIndex = #state.bullets, 1, -1 do local bullet = state.bullets[bulletIndex] bullet.timeLeft = bullet.timeLeft - dt @@ -127,7 +119,7 @@ function love.update(dt) end for asteroidIndex = #state.asteroids, 1, -1 do local asteroid = state.asteroids[asteroidIndex] - if intersects(bullet, asteroid) 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) @@ -160,7 +152,7 @@ function love.update(dt) for _, asteroid in ipairs(state.asteroids) do update(asteroid, dt) - if areCirclesIntersecting(state.ship.x, state.ship.y, game.ship.radius, asteroid.x, asteroid.y, asteroid.radius) then + if phys.intersects(state.ship, asteroid) then reset() break end diff --git a/asteroids/phys.lua b/asteroids/phys.lua new file mode 100644 index 0000000..edc5920 --- /dev/null +++ b/asteroids/phys.lua @@ -0,0 +1,18 @@ +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 +-- TODO spin +function phys.update(actor, dt) + local dv = actor.speed * dt + actor.x = actor.x + math.cos(actor.angle) * dv + actor.y = actor.y + math.sin(actor.angle) * dv +end + +return phys