Skip to content

Instantly share code, notes, and snippets.

@sealgair
Created January 9, 2017 18:37
Show Gist options
  • Save sealgair/cd61686a73774893d5fa8e1309c072d3 to your computer and use it in GitHub Desktop.
Save sealgair/cd61686a73774893d5fa8e1309c072d3 to your computer and use it in GitHub Desktop.
-- class maker
function class(proto, base)
proto = proto or {}
proto.__index = proto
setmetatable(proto, {
__index = base,
__call = function(cls, ...)
local self = setmetatable({
type=proto
}, proto)
if(self.init) self:init(...)
return self
end
})
proto.subclass = function(subproto)
return class(subproto, proto)
end
return proto
end
--------------------------------
-- particles
--------------------------------
partgen=class()
function partgen:init(args)
-- required args
self.x=args.x
self.y=args.y
-- optional args
self.colors=args.colors or {args.color} or {7}
self.dur=args.duration or maxnum
self.rate=args.rate or 10
self.pdur=args.partduration or .2
self.actor=args.actor
self.particles={}
self.age=0
self.pcount=0
end
-- have i finished drawing
function partgen:done()
return self.age>self.dur and #self.particles<=0
end
function partgen:stop()
self.dur=0
end
function partgen:newpart()
local p={
x=self.x, y=self.y,
c=rndchoice(self.colors),
vel={x=rnd(200)-100, y=-rnd(100)},
age=0,
}
if self.actor then
p.x+=self.actor.x
p.y+=self.actor.y
end
return p
end
function partgen:update()
if self.age<=self.dur then
self.age+=dt
while self.pcount < self.rate*self.age do
add(self.particles, self:newpart())
self.pcount+=1
end
end
for p in all(self.particles) do
p.age+=dt
if p.age>=self.pdur then
del(self.particles, p)
else
p.x+=p.vel.x*dt
p.y+=p.vel.y*dt
p.vel.y+=g*dt
end
end
end
function partgen:draw(o)
for p in all(self.particles) do
pset(p.x, p.y, p.c)
end
end
--------------------------------
-- example usage
--------------------------------
-- table containing all known particle generators
local particles = {}
-- create particle system for water splashes (short duration, shades of blue)
add(particles, partgen{
x=self.x+4, y=self.y+4,
colors={7,12,1,13},
duration=0.1,
rate=20,
})
function _update()
-- update states & positions of particles
for p in all(particles) do
p.update()
end
end
function _draw()
-- draw
for p in all(particles) do
p.draw()
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment