-
Notifications
You must be signed in to change notification settings - Fork 2
/
camera.lua
92 lines (74 loc) · 1.86 KB
/
camera.lua
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
local Transform = require 'component/transform'
local camera = {
pos = Vec2.ZERO(),
scaleX = 1,
scaleY = 1,
offset = Vec2.ZERO(),
follow_target = nil
}
function camera:reset()
self.pos = Vec2.ZERO()
self.scaleX, self.scaleY = 1, 1
self.offset = Vec2.ZERO()
self.follow_target = nil
end
function camera:setPos(x, y)
if not y then -- if only a vector is fed
self.pos.x = x.x
self.pos.y = x.y
end
self.pos.x = x
self.pos.y = y
end
function camera:follow(entity)
self.follow_target = entity:get_component(Transform)
end
function camera:update(dt)
if not self.follow_target.pos then return end
self.pos.x = self.follow_target.pos.x - (NATIVE_WIDTH * self.scaleX) / 2
self.pos.y = self.follow_target.pos.y - (NATIVE_HEIGHT * self.scaleY) / 2
end
function camera:set()
love.graphics.push()
love.graphics.scale(1 / self.scaleX, 1 / self.scaleY)
love.graphics.translate(-(self.pos.x + self.offset.x),
-(self.pos.y + self.offset.y))
end
function camera:unset()
love.graphics.pop()
end
function camera:zoom(z)
self.scaleX = 1 / z
self.scaleY = 1 / z
end
function camera:get_zoom()
return 1 / self.scaleX
end
function camera:scale(sx, sy)
self.scaleX = self.scaleX * sx
self.scaleY = self.scaleY * sy
end
function camera:toScreenX(x)
return (x - self.pos.x) / self.scaleX
end
function camera:toScreenY(y)
return (y - self.pos.y) / self.scaleY
end
function camera:toWorldX(x)
return (x * self.scaleX) + self.pos.x
end
function camera:toWorldY(y)
return (y * self.scaleY) + self.pos.y
end
function camera:toWorldPos(vec)
local x = (vec.x * self.scaleX) + self.pos.x
local y = (vec.y * self.scaleY) + self.pos.y
return Vec2(x, y)
end
function camera:toScreenPos(vec)
return Vec2(self:toScreenX(vec.x), self:toScreenY(vec.y))
end
function camera:move(vel)
self.pos = self.pos + vel
end
return camera