Files
cell/scripts/particle.js
2025-01-21 16:46:18 -06:00

117 lines
2.4 KiB
JavaScript

var Color = use('color')
var ex = {}
var emitter = {};
emitter.life = 10;
emitter.scale = 1;
emitter.grow_for = 0;
emitter.spawn_timer = 0;
emitter.pps = 0;
emitter.color = Color.white;
emitter.kill = function () {
emitters.remove(this);
};
var std_step = function (p) {
if (p.time < this.grow_for) {
var s = Math.lerp(0, this.scale, p.time / this.grow_for);
p.transform.scale = s;
} else if (p.time > p.life - this.shrink_for) {
var s = Math.lerp(0, this.scale, (p.life - p.time) / this.shrink_for);
p.transform.scale = s;
} else p.transform.scale = [this.scale, this.scale, this.scale];
};
emitter.step_hook = std_step;
emitter.spawn = function (t) {
t ??= this.transform;
var par = this.dead.shift();
if (par) {
par.transform.unit();
par.transform.pos = t.pos;
par.transform.scale = this.scale;
this.particles.push(par);
par.time = 0;
this.spawn_hook?.(par);
par.life = this.life;
return;
}
par = {
transform: os.make_transform(),
life: this.life,
time: 0,
color: this.color,
body:{},
};
par.transform.scale = this.scale;
this.particles.push(par);
this.spawn_hook(par);
};
emitter.step = function step(dt) {
// update spawning particles
if (this.on && this.pps > 0) {
this.spawn_timer += dt;
var pp = 1 / this.pps;
while (this.spawn_timer > pp) {
this.spawn_timer -= pp;
this.spawn();
}
}
// update all particles
for (var p of this.particles) {
p.time += dt;
p.transform.move(p.body.velocity?.scale(dt));
this.step_hook?.(p);
if (this.kill_hook?.(p) || p.time >= p.life) {
this.die_hook?.(p);
this.dead.push(p);
this.particles.remove(p);
}
}
// for (var p of this.particles)
// p.transform.clean();
};
emitter.burst = function (count, t) {
for (var i = 0; i < count; i++) this.spawn(t);
};
var emitters = [];
ex.make = function make_emitter() {
var e = Object.create(emitter);
e.particles = [];
e.dead = [];
emitters.push(e);
return e;
};
ex.update = function update_emitters(dt) {
for (var e of emitters) e.step(dt);
}
ex.stat = function stat_emitters()
{
var stat = {};
stat.emitters = emitters.length;
var particles = 0;
for (var e of emitters) particles += e.particles.length;
stat.particles = particles;
return stat;
}
ex.all = function all_emitters() { return emitters; }
return ex