xxxxxxxxxx
189
let myFireflies = [];
let howMany;
//let osc ,env, decTime;
//let oscTimer, oscTimerMax;
let size;
function setup() {
createCanvas(500, 500);
howMany = 2;
for(let i=0; i<howMany; i++)
{
myFireflies.push(new Firefly(random(1,10),0,0));
}
//myFireflies = new Firefly(10,width/2,height/2);
noStroke();
}
function draw() {
background(250);
for(let i=0; i< howMany; i++)
{
myFireflies[i].update();
myFireflies[i].display();
myFireflies[i].playSound();
}
//oscTimerMax = 100;
//print(myGuy.vel.mag());
// let c = 0.1;
// let normal = 1;
// let frictionMag = c * normal;
// let friction = myGuy.vel.copy();
// friction.mult(-1);
// friction.normalize();
// friction.mult(frictionMag);
//myGuy.applyForce(friction);
}
class Firefly{
constructor(tmass, tx, ty){
this.mass = tmass;
this.pos = createVector(tx, ty);
this.vel = createVector(10,10);
this.acc = createVector(0,0);
this.mScale = 1;
this.drag = createVector(0.5,0.5);
//Movement
this.timer = 0;
this.timeMax = 100;
this.speed = 10;
this.myForce = createVector(random(-this.speed,this.speed),random(-this.speed,this.speed));
//Sound
this.env = new p5.Envelope();
this.env.setADSR(0.03,0.05,0,0.01);
this.env.setRange(1,0);
this.osc = new p5.Oscillator();
this.osc.setType('sine');
this.osc.amp(this.env);
this.osc.start();
this.osc.freq(800);
this.oscTimer=0;
this.oscTimerMax=0;
this.freqLow = random(600,800);
this.freqHigh = random(900,1000);
//this.size = 10;
}
applyForce(force){
//this.vel.div(2);
//force = Mass * acceleration
let f = p5.Vector.div(force,this.mass);
this.vel.add(f);
}
update(){
// this.vel.x/=1.2;
// this.vel.y/=1.2;
this.vel.div(1.02);
//this.vel.add(this.acc);
this.pos.add(this.vel);
this.acc.mult(0);
this.timer++;
if(this.timer > this.timeMax)
{
this.timer = 0;
this.speed = random(4,20);
this.myForce = createVector(random(-this.speed,this.speed),random(-this.speed,this.speed));
//console.log(myForce);
this.vel = this.myForce;
this.timeMax = ceil(random(80,120));
}
//PACMANING
if(this.pos.x < 0)
{
this.pos.x = width;
}
if(this.pos.x > width)
{
this.pos.x = 0;
}
if(this.pos.y < 0)
{
this.pos.y = height;
}
if(this.pos.y > height)
{
this.pos.y = 0;
}
///
}
display(){
fill(240,200,0);
this.size = map(this.vel.mag(),0,15,15,5)
this.size = constrain(this.size, 5,15);
ellipse(this.pos.x,this.pos.y,this.size,this.size);
}
playSound(){
this.oscTimerMax = map(this.vel.mag(),0,10,20,7);
//original frequency range is 900 to 1600
this.osc.freq(map(this.vel.mag(),0,10,this.freqLow,this.freqHigh));
this.oscTimer++;
if(this.oscTimer > this.oscTimerMax){
this.osc.pan(map(this.pos.x,0,width, -1.0,1.0));
this.env.play();
this.oscTimer = 0;
fill(0);
ellipse(this.pos.x,this.pos.y,this.size,this.size);
}
}
}