summaryrefslogtreecommitdiff
path: root/physics.lua
diff options
context:
space:
mode:
Diffstat (limited to 'physics.lua')
-rw-r--r--physics.lua70
1 files changed, 70 insertions, 0 deletions
diff --git a/physics.lua b/physics.lua
new file mode 100644
index 0000000..336a7c2
--- /dev/null
+++ b/physics.lua
@@ -0,0 +1,70 @@
+local game = require 'game'
+
+local M = {}
+
+love.physics.setMeter(300)
+M.world = love.physics.newWorld(0, 2000)
+M.Object = game.Object:extend()
+
+local bodies = {}
+setmetatable(bodies, {__mode = 'kv'})
+function M.body_object(body)
+ return bodies[body]
+end
+
+function M.Object:new(pos, rotation, scale, type)
+ game.Object.new(self, pos, rotation, scale)
+ local x, y = unpack(self.pos)
+ self.body = love.physics.newBody(M.world, x, y, type)
+ self.body:setAngle(self.rot)
+ bodies[self.body] = self
+end
+
+function M.Object:enable()
+ game.Object.enable(self)
+ if body then
+ self.body:setActive(true)
+ end
+end
+
+function M.Object:disable()
+ game.Object.disable(self)
+ self.body:setActive(false)
+end
+
+function M.Object:update()
+ local x, y = self.body:getWorldPoint(0, 0)
+ self.pos[1], self.pos[2] = x, y
+ self.rot = self.body:getAngle()
+end
+
+local sprites = {}
+setmetatable(sprites, {__mode = 'v'})
+
+function M.simple(sprite, shape, body_type, restitution)
+ local class = M.Object:extend()
+ if type(sprite) == 'string' then
+ sprite = sprites[sprite] or love.graphics.newImage(sprite, {dpiscale = 2})
+ end
+ class.sprite = sprite
+
+ local w, h = sprite:getDimensions()
+ function class:new(pos, rotation, scale)
+ M.Object.new(self, pos, rotation, scale, body_type or 'dynamic')
+
+ if not shape or shape == 'rect' then
+ self.shape = love.physics.newRectangleShape(w, h)
+ elseif shape == 'circle' then
+ self.shape = love.physics.newCircleShape(w / 2)
+ else
+ self.shape = love.physics.newPolygonShape(unpack(shape))
+ end
+ self.fixture = love.physics.newFixture(self.body, self.shape)
+ if restitution then
+ self.fixture:setRestitution(restitution)
+ end
+ end
+ return class
+end
+
+return M