Hi everyone here, I’m a newbie learning P5.js to do something interactive.
I’m facing a problem with I want to generate a particle system when receive a trigger from microphone. But when the trigger is on, the particle system will continuously generate.
I only want to generate one when triggered and if the trigger is off, then delete the particle system.
sketch.js
var systems
var mic
function setup() {
c = createCanvas(1280,720);
background(100);
systems = []
//for audio setting
mic = new p5.AudioIn()
mic.start()
}
function draw() {
background(20, 10);
var micLevel = mic.getLevel() * 1000
console.log(micLevel)
for (let i = 0; i < systems.length; i++) {
systems[i].addBoid()
systems[i].render()
}
// if micLevel over the threshold add a new BoidSystem
if (micLevel > 40) {
this.bs = new BoidSystem(createVector(679, 548))
systems.push(bs)
}
if (micLevel < 40) {
this.systems.splice(this.bs, 1)
}
}
//can also add BoidSystem with Mouse
function mousePressed() {
this.bs = new BoidSystem(createVector(mouseX, mouseY))
systems.push(bs)
}
Boid class
var colors = "156064-00c49a-f8e16c-ffc2b4-fb8f67".split("-").map(a => "#" + a)
class Boid {
constructor(position) {
this.pos = position.copy() || createVector(width / 2, height / 2)
this.target = createVector(0, 0)
this.vel = createVector(0, 0)
this.acc = p5.Vector.random2D().setMag(random(2, 8))
this.r = 3
this.color = random(colors)
this.lifespan = 1600
}
run() {
this.update()
this.show()
}
update() {
this.target = createVector(100, height / 2)
this.pos.add(this.vel)
this.vel = this.target.sub(this.pos).limit(3)
this.acc.x+=(noise(this.pos.x)*0.1)
this.acc.y+=(noise(this.pos.y)*0.1)
this.vel.add(this.acc)
this.acc.mult(0.94)
this.lifespan -= 18
//check border
if (this.pos.x > width || this.pos.x < 0) {
this.vel.x *= -1
}
if (this.pos.y > width || this.pos.y < 0) {
this.vel.y *= -1
}
}
show() {
// POINT boids
push()
translate(this.pos.x, this.pos.y)
fill(this.color)
noStroke()
ellipse(0, 0, this.r)
pop()
}
isDead() {
return this.vel.mag() < 0.2
}
}
BoidSystem class
class BoidSystem {
constructor(position) {
this.origin = position.copy()
this.boids = []
}
addBoid() {
this.boids.push(new Boid(this.origin))
}
render() {
for (let i = this.boids.length - 1; i >= 0; i--) {
let boid = this.boids[i]
boid.run()
if (boid.isDead()) {
this.boids.splice(boid, 1)
}
}
}
}