summaryrefslogtreecommitdiff
path: root/src/systems/particle.js
diff options
context:
space:
mode:
authorLogan Hunt <loganhunt@simponic.xyz>2022-04-11 16:55:16 -0600
committerLogan Hunt <loganhunt@simponic.xyz>2022-04-11 16:55:16 -0600
commit491f532750da38f17e2891042bcb03f095ec4d92 (patch)
tree8319ee79d4ea65afd8f6eaf75c5a94d9a72ea1a1 /src/systems/particle.js
parentec7b01918cc2aec22d4c408bdd460bf767377fbc (diff)
downloadbbiy-491f532750da38f17e2891042bcb03f095ec4d92.tar.gz
bbiy-491f532750da38f17e2891042bcb03f095ec4d92.zip
Move particle stuff to a system to simplify spawning particles
Diffstat (limited to 'src/systems/particle.js')
-rw-r--r--src/systems/particle.js57
1 files changed, 57 insertions, 0 deletions
diff --git a/src/systems/particle.js b/src/systems/particle.js
new file mode 100644
index 0000000..e58c0a0
--- /dev/null
+++ b/src/systems/particle.js
@@ -0,0 +1,57 @@
+game.system.Particle = () => {
+ "use strict";
+ const particleSpawners = {};
+
+ const particleSpawner = ({colors, maxAmount, minAmount, minLife, maxLife, minRadius, maxRadius, maxSpeed, spawnFunction}) => {
+ return Array(randomInRange(minAmount, maxAmount)).fill(0).map(() => {
+ let particleSpec = {
+ x: Math.random(),
+ y: Math.random(),
+ dx: Math.random() * maxSpeed - maxSpeed / 2,
+ dy: Math.random() * maxSpeed - maxSpeed / 2,
+ radius: randomInRange(minRadius, maxRadius),
+ color: colors[randomInRange(0, colors.length-1)],
+ lifetime: randomInRange(minLife, maxLife),
+ elapsed: 0,
+ };
+ if (spawnFunction) {
+ particleSpec = {...particleSpec, ...spawnFunction(particleSpec)};
+ }
+ return particleSpec;
+ });
+ }
+
+ const update = (elapsedTime, entities, _changedIds) => {
+ for (let id in entities) {
+ const entity = entities[id];
+ if (entity.hasComponent("particles")) {
+ if (!particleSpawners[entity.id]) {
+ particleSpawners[entity.id] = particleSpawner(entity.components.particles.spec.spec);
+ entities[id].particleSprite = game.graphics.Sprite({
+ drawFunction: (elapsedTime, {x, y, width, height}, context) => {
+ let particleSpawner = particleSpawners[entity.id];
+ particleSpawner.map((particleSpec) => particleSpec.elapsed += elapsedTime);
+ particleSpawners[id] = particleSpawner.filter((particleSpec) => particleSpec.lifetime > particleSpec.elapsed);
+ particleSpawner = particleSpawners[id];
+ if (particleSpawner.length === 0) {
+ entities[id].removeComponent("alive");
+ }
+ particleSpawner.map((particleSpec) => {
+ const position = {x: (particleSpec.x * width) + x + particleSpec.dx * particleSpec.elapsed, y: (particleSpec.y * height) + y + particleSpec.dy * particleSpec.elapsed};
+ const fill = context.fillStyle;
+ context.fillStyle = particleSpec.color;
+ context.beginPath();
+ context.arc(position.x, position.y, particleSpec.radius, 0, 2 * Math.PI);
+ context.fill();
+ context.fillStyle = fill;
+ });
+ }
+ });
+ }
+ }
+ }
+ return new Set();
+ };
+
+ return { update };
+};