Skip to content

Commit

Permalink
Merge pull request #3 from JoelDesante/deletable-emitters
Browse files Browse the repository at this point in the history
Deletable emitters
  • Loading branch information
joeldesante committed Jan 15, 2021
2 parents 8aab537 + 4f5021b commit 54bd384
Showing 1 changed file with 35 additions and 5 deletions.
40 changes: 35 additions & 5 deletions src/ParticleEmitter/init.lua
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@ local function spawnParticle(hook, particleElement, onSpawn)
return particle;
end

--[[
Creates a new particle emitter.
hook - This is the UI element which the particle emitter will latch on to.
particleElement - This is the UI element which will be used as the particle.
]]
function ParticleEmitter.new(hook, particleElement)
local self = {};
self.particles = {};
Expand All @@ -19,9 +24,9 @@ function ParticleEmitter.new(hook, particleElement)
self.onSpawn = function(p) end

-- Internal Values
self.__dead = false; -- True when the emitter is destroyed
self.__elapsedTime = 0;

game:GetService("RunService").Heartbeat:Connect(function(delta)
self.__runServiceConnection = game:GetService("RunService").Heartbeat:Connect(function(delta)
self.__elapsedTime = self.__elapsedTime + delta;
for index, particle in ipairs(self.particles) do
if particle.isDead then
Expand All @@ -35,13 +40,38 @@ function ParticleEmitter.new(hook, particleElement)
This loop will time the particle spawns so that the
given rate can be achieved.
]]
while self.__elapsedTime >= (1/self.rate) do
table.insert(self.particles, spawnParticle(self.hook, self.particleElement, self.onSpawn));
self.__elapsedTime = self.__elapsedTime - (1/self.rate);
if self.rate > 0 and (self.__dead == false) then -- Note: 1/0 results as `inf` in lua.
while self.__elapsedTime >= (1/self.rate) do
table.insert(self.particles, spawnParticle(self.hook, self.particleElement, self.onSpawn));
self.__elapsedTime = self.__elapsedTime - (1/self.rate);
end
end
end)

return setmetatable(self, {__index = ParticleEmitter});
end

--[[
Destroys the particle emitter.
]]
function ParticleEmitter:Destroy()

if self.__dead then
error('Cannot destroy dead particle emitter.');
return;
end

self.__dead = true;
for _,particle in ipairs(self.particles) do
if particle then
particle:Destroy(); -- Flags all the particles for removal.
end
end

-- Make disconnections
if self.__runServiceConnection then
self.__runServiceConnection:Disconnect();
end
end

return ParticleEmitter;

0 comments on commit 54bd384

Please sign in to comment.