1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
local coords = require"common.coords"
local class = require"common.class"
-- in screen units
-- zoom is screen pixels per world unit
local Camera = class()
function Camera.make(cls,pos,zoom)
pos = pos or coords.Pos:make(0,0)
zoom = zoom or 30
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 coords.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(coords.Pos:make(0,0)),
self:screen_to_world(coords.Pos:make(W,H))
end
return {Camera=Camera}
|