Processing テクニック集

1回おきに(交互に)繰り返す

int n = 10;
for(int i = 0; i < n; i++){
  if(i % 2 == 0){
    fill(0);
  }
  else{
    fill(255);
  }
  rect(0, i * height / n, width, height / n);
}

考えてみよう:3回に1回、色を変えながら繰り返す

条件分岐をコンパクトに書く(動作は上のプログラムと同じ)

int n = 10;
for(int i = 0; i < n; i++){
  fill(i % 2 == 0 ? 0 : 255);
  rect(0, i * height / n, width, height / n);
}

四角形の中にあるかどうかを条件にする

float x, y, size;

void setup(){
  x = random(width);
  y = random(height);
  size = 20;
}

void draw(){
  background(255);
  if(mouseX > x && mouseX < x + size && mouseY > y && mouseY < y + size){
    fill(0);
  }
  else{
    fill(255);
  }
  rect(x, y, size, size);
}

横方向にグラデーション塗り

for(int i = 0; i < width; i++){
  int c = 255 * i / width;
  stroke(c);
  line(i, 0, i, height);
}

考えてみよう:縦方向にグラデーション塗り

考えてみよう:放射状にグラデーション塗り

虹のように色を変えるグラデーション塗り

colorMode(HSB);

for(int i = 0; i < width; i++){
  int c = 255 * i / width;
  stroke(c, 200, 200);
  line(i, 0, i, height);
}

配列を作成して、ランダムな値を代入する

int[] scores = new int[10];
for(int i = 0; i < scores.length; i++){
  scores[i] = ceil(random(60, 100));
  println(scores[i]);
}

合計を求める

int sum = 0;
for(int i = 0; i < scores.length; i++){
  sum += scores[i];
}
println(sum);

思い出してみよう:平均値を求める

一番○○なデータを見つける

int best = scores[0];
for(int i = 1; i < scores.length; i++){
  if(best より scores[i] の方が○○なら){
    best = scores[i];
  }
}

思い出してみよう:最大値・最小値を求める

条件に合うものがいくつあるか数える

int count = 0;
for(int i = 0; i < scores.length; i++){
  if(条件){
    count++;
  }
}

考えてみよう:条件に合うものの平均値を求める

2つずつ組にして繰り返す

// 重複ありで2つずつ
for(int i = 0; i < scores.length - 1; i++){ // - 1 しないとダメなのに注意
  println(scores[i] + "," + scores[i + 1]);
}

// 重複なしで2つずつ
for(int i = 0; i < scores.length - 1; i += 2){ // - 1 しないとダメなのに注意
  println(scores[i] + "," + scores[i + 1]);
}

考えてみよう:3つずつ組にして繰り返す

上下左右に移動する

int x, y;

void setup(){
  x = ceil(random(width));
  y = ceil(random(height));
}

void draw(){
  background(0);
  ellipse(x, y, 4, 4);
  x += 1; // move right
  // x += 2; move right faster
  // x -= 1; // move left
  // y += 1; // move down
  // y -= 1; // move up
}

考えてみよう:斜めに移動する

画面の右端に着くと、反対側から出てくる (setup までは上と同じ)

void draw(){
  background(0);
  ellipse(x, y, 4, 4);
  x += 1;
  x = x % width; // 割った余りを使うのがポイント
}

考えてみよう:画面の左・上・下端に着くと、反対側から出てくる

画面の左右端で跳ね返る

int x, y, vx;

void setup(){
  x = ceil(random(width));
  y = ceil(random(height));
  vx = 1; // 速度用の変数
}

void draw(){
  background(0);
  ellipse(x, y, 4, 4);
  x += vx; // 速度の分、座標を変える
  if(x > width || x < 0){ // 画面外に出たら
    vx = -vx; // 速度を逆向きにする
  }
}

考えてみよう:画面の上下端で跳ね返る

考えてみよう:画面端ではない、好きなところで跳ね返る

だんだん大きくなる

int r;

void setup(){
  r = 10;
}

void draw(){
  ellipse(width / 2, height / 2, r, r);
  r += 1;
}

考えてみよう:大きくなったり、小さくなったりする

考えてみよう:だんだん色が変わる

void draw() {
  background(255);
  if (frameCount / 10 % 2 == 0) { // frameCount % 2 == 0 だと速すぎ
    fill(0);
  }
  else{
    fill(255);
  }
  rect(0, 0, width, height);
}

考えてみよう:チカチカする速さを変えてみよう

考えてみよう:チカチカしながら動く

考えてみよう:マウスで指したときだけチカチカする