Daily Creative Coding

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

パーティクルの衝突に合わせて音を鳴らす

f:id:aa_debdeb:20161101201339j:plain
/**
* sound by particle's crash
*
* @author aa_debdeb
* @date 2016/11/09
*/

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

Minim minim;
ArrayList<Particle> particles;

void setup(){
  size(640, 640);
  stroke(0);
  minim = new Minim(this);
  particles = new ArrayList<Particle>();
  for(int i = 0; i < 10; i++){
    particles.add(new Particle());
  }
}

void draw(){
  background(255);
  for(Particle p: particles){
    p.update();
    p.display();
    if(p.isCollided){
      p.playSound();
    }
  }
}

class Particle{
  
  PVector loc, vel;
  float radius = 20;
  boolean isCollided = false;
  AudioPlayer player;
  
  Particle(){
    loc = new PVector(random(radius, width - radius), random(radius, height - radius));
    vel = new PVector(random(-3, 3), random(-3, 3));
    player = minim.loadFile("clap.mp3");
  }
  
  void display(){
    if(isCollided){
      noStroke();
      fill(255, 0, 0);
    } else {
      stroke(0);
      noFill();
    }
    ellipse(loc.x, loc.y, radius * 2, radius * 2);
  }
  
  void update(){
    loc.add(vel);
    if(loc.x <= radius || loc.x >= width - radius){
      vel.x *= -1;
      loc.x += vel.x;
      isCollided = true;
    }
    if(loc.y <= radius || loc.y >= height - radius){
      vel.y *= -1;
      loc.y += vel.y;
      isCollided = true;
    }
  }
  
  void playSound(){
    player.play();
    player.rewind();
    isCollided = false;
  }
}