Daily Creative Coding

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

相反する2つの重力

/**
* contrary gravity
*
* @author aa_debdeb
* @date 2016/05/01
*/

ArrayList<Particle> particles;
float nOffset1, nOffset2;
float nScale1 = 0.01;
float nScale2 = 0.004;
float gravity = 0.3;
float velMax = 5.0;
color c1 = color(255, 0, 255);
color c2 = color(255, 213, 0);

void setup(){
  size(500, 500);
  particles = new ArrayList<Particle>();
  for(int i = 0; i < 1000; i++){
    particles.add(new Particle());
  }
  nOffset1 = random(10000);
  nOffset2 = random(10000);
}

void draw(){
  background(32);
  for(Particle particle: particles){
    particle.update();
    particle.display();
  }
}

class Particle{

  PVector pos, vel;
  float rad = 3;
  color c;
  
  Particle(){
    pos = new PVector(random(rad, width - rad), random(rad, height - rad));
    float velAng = random(TWO_PI);
    float velSize = random(velMax);
    vel = new PVector(velSize * cos(velAng), velSize * sin(velAng));
  }
  
  void update(){
    vel.y *= 0.995;
    float noiseVal = noise(nOffset1 + pos.x * nScale1, nOffset2 + frameCount * nScale2); 
    float acc = -gravity * noiseVal + gravity * (1.0 - noiseVal);
    vel.y += acc;
    constrain(vel.y, -velMax, velMax);
    pos.add(vel);
    if(pos.x < rad){
      pos.x = rad;
      vel.x *= -1;
    }
    if(pos.x >= width - rad){
      pos.x = width - rad;
      vel.x *= -1;
    }
    if(pos.y < rad){
      pos.y = rad;
      vel.y *= -1;
    }
    if(pos.y >= height - rad){
      pos.y = height - rad;
      vel.y *= -1;
    }
    c = color(red(c1) * noiseVal + red(c2) * (1.0 - noiseVal), green(c1) * noiseVal + green(c2) * (1.0 - noiseVal), blue(c1) * noiseVal + blue(c2) * (1.0 - noiseVal)); 
  }
  
  void display(){
    noStroke();
    fill(c, 196);
    ellipse(pos.x, pos.y, rad * 2, rad * 2);
  }
  
}