-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworld.lua
83 lines (64 loc) · 1.92 KB
/
world.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
require("class")
require("spatialgrid")
require("emitter")
require("particles/hydrogen")
require("particles/oxygen")
require("particles/lava")
require("particles/block")
require("particles/plant")
require("particles/smoke")
-- World contains the emitters and such.
World = class()
function World:_init()
self.placedEmitters = {}
self.placedBlocks = {}
-- The grid which is used for broad-phased collision detection.
self.spatialGrid = SpatialGrid()
end
function World:addBlock(x, y)
local b = Block()
b.x = math.floor(x / b.size) * b.size
b.y = math.floor(y / b.size) * b.size
print(string.format("Placing block at %3d, $3d", b.x, b.y))
table.insert(self.placedBlocks, b)
end
-- Generator function is a function which returns a new Particle.
function World:addEmitter(emitter)
emitter.world = self
table.insert(self.placedEmitters, emitter)
end
function World:setGridSize(delta)
if delta > 0 then
self.spatialGrid.gridSize = self.spatialGrid.gridSize + 1
elseif delta < 0 then
self.spatialGrid.gridSize = math.max(1, self.spatialGrid.gridSize - 1)
end
self.spatialGrid:reinitialize()
end
function World:update(dt)
-- Check emitters if some are eligible for removal (life is less than zero,
-- and all particles in the emitter are dead)
table.removeif(self.placedEmitters, function(p) return p:isExpired() end)
self.spatialGrid:reinitialize()
for _, emitter in ipairs(self.placedEmitters) do
emitter:update(dt)
-- Add all particles to the spatial grid, for the broadphase collision
-- detection before narrowing it down.
for _, v in ipairs(emitter.particles) do
self.spatialGrid:addParticle(v)
end
end
for _, block in ipairs(self.placedBlocks) do
self.spatialGrid:addParticle(block)
end
self.spatialGrid:checkCollisions()
end
function World:draw()
self.spatialGrid:draw()
for i, emitter in ipairs(self.placedEmitters) do
emitter:draw()
end
for _, v in ipairs(self.placedBlocks) do
v:draw()
end
end