diff options
author | ubq323 <ubq323@ubq323.website> | 2025-02-17 14:48:34 +0000 |
---|---|---|
committer | ubq323 <ubq323@ubq323.website> | 2025-02-17 14:48:34 +0000 |
commit | f1492b52414b6f2ad6cfff45375c08677feab18c (patch) | |
tree | 2eac341c813f513b4acef7ff591f6f68936eb334 /camera.lua |
initial
Diffstat (limited to 'camera.lua')
-rw-r--r-- | camera.lua | 46 |
1 files changed, 46 insertions, 0 deletions
diff --git a/camera.lua b/camera.lua new file mode 100644 index 0000000..19c5bd4 --- /dev/null +++ b/camera.lua @@ -0,0 +1,46 @@ +local class = require'r.class' +local Pos = require'r.pos' + +-- in screen units + +-- zoom is screen pixels per world unit +local Camera = class() +function Camera.make(cls,pos,zoom) + pos = pos or Pos:make(0,0) + zoom = zoom or 1 + return setmetatable({pos=pos,zoom=zoom},cls) +end +local function screen_offset() + -- in screen units, not in world units ! + local W,H = love.graphics.getDimensions() + return Pos:make(W/2,H/2) +end +function Camera.apply_trans(self) + local so = screen_offset() + + -- centre (0,0) in the middle of the screen + love.graphics.translate(so.x,so.y) + + -- apply camera transformations + love.graphics.scale(self.zoom) + love.graphics.translate(-self.pos.x,-self.pos.y) +end + +function Camera.screen_to_world(self,pos) + local so = screen_offset() + return (pos-so)/self.zoom + self.pos +end +function Camera.world_to_screen(self,pos) + local so = screen_offset() + return (pos-self.pos) * self.zoom + so +end + +function Camera.extents(self) + local W,H = love.graphics.getDimensions() + -- returns top left and bottom right pos's in world coords + return self:screen_to_world(Pos:make(0,0)), + self:screen_to_world(Pos:make(W,H)) +end + + +return Camera |