読者です 読者をやめる 読者になる 読者になる

Daily Creative Coding

元「30 min. Processing」。毎日、Creative Codingします。

音量に応じてパーティクルにノイズを加える

サウンド パーティクル
f:id:aa_debdeb:20151214145928j:plain
/**
* Particles Controlled by Sound
*
* @author aa_debdeb
* @date 2015/12/23
*/

import ddf.minim.*;
import ddf.minim.analysis.*;
import ddf.minim.effects.*;
import ddf.minim.signals.*;
import ddf.minim.spi.*;
import ddf.minim.ugens.*;

int PARTICLE_NUM = 3000;
float PARTICLE_RADIOUS = 1.5;
float PARTICLE_MAX_SPEED = 10.0;
float PARTICLE_MAX_ACCELERATION = 1.0;
float PARTICLE_MAX_SPEED_VARIANT = 100.0;
float MAX_VOLUME = 2.0;

Minim minim;
AudioInput in;

Particle[] particles;

void setup(){
  size(500, 500);
  smooth();
  frameRate(60);
  minim = new Minim(this);
  in = minim.getLineIn(Minim.STEREO, 512);
  
  particles = new Particle[PARTICLE_NUM];
  for(int i = 0; i < PARTICLE_NUM; i++){
    particles[i] = new Particle();
  }
}

void draw(){
  background(255);
  
  for(Particle particle: particles){
    particle.display();
    particle.update(in.mix.level());
  }    
}

class Particle{
  
  PVector position;
  PVector velocity;
  
  Particle(){
    position = new PVector(random(width), random(height));
    setRandomVelocity();
  }
  
  void setRandomVelocity(){
    velocity = new PVector(random(2) - 1.0, random(2) - 1.0);
    velocity.normalize();
    velocity.mult(random(PARTICLE_MAX_SPEED * 2) - PARTICLE_MAX_SPEED);
  }

  void display(){
    noStroke();
    fill(map(velocity.mag(), 0, PARTICLE_MAX_SPEED, 230, 20), 200);
    ellipse(position.x, position.y, PARTICLE_RADIOUS * 2, PARTICLE_RADIOUS * 2);
  }
  
  void update(float volume){
    PVector mouse = new PVector(mouseX, mouseY);
    PVector direction = PVector.sub(mouse, position);
    direction.normalize();
    PVector acceleration = PVector.mult(direction, PARTICLE_MAX_ACCELERATION);
    velocity.add(acceleration);
    PVector velocityVariant = PVector.random2D();
    velocityVariant.normalize();
    velocityVariant.mult(map(constrain(sq(volume), 0, MAX_VOLUME), 0, MAX_VOLUME, 0, PARTICLE_MAX_SPEED_VARIANT));
    velocity.add(velocityVariant);
    velocity.limit(PARTICLE_MAX_SPEED);
    position.add(velocity);
  }
 
}