LoginSignup
1
1

More than 1 year has passed since last update.

forループを使った簡単なインタラクション

Posted at

forループで簡単なインタラクション

p5js初めたての方が真似しやすいコードを紹介します。

準備

p5jsのセッティングは済ませているものと仮定。
今回はラジアンを使って円を描くので、円周角の考え方も必要となる。

早速本題のコード

まず、インタラクションのベースとなる、円周上へのサークルの配置から始める。
円周角2πを分割する数として、変数segmentを用意。

let segment = 100;

次に、このsegmentで割った角度ごとにサークルを配置。

for(let i=0; i<segment; i++){
circle(100*Math.cos(i*Math.PI*2/segment),100*Math.sin(i*Math.PI*2/segment),100);
}

スクリーンショット 2022-12-09 21.57.38.png

main.js
let cx;
let cy;
let W;
let H;

function setup() {
  createCanvas(windowWidth, windowHeight);
  background(100);
  cx = windowWidth / 2;
  cy = windowHeight / 2;
  W = windowWidth;
  H = windowHeight;
}

function draw() {
  background(100);

  noFill();
  translate(cx,cy);

  for(let i=0;i<100;i++){

    stroke(250,0,250);
    circle(200*Math.cos(i*Math.PI*2/100),200*Math.sin(i*Math.PI*2/100),100);

  }
}

さて、たとえ、drawが呼び出され続けても、このままでは、静止画同様の描画なので、これを動かすために、以下の変数を用意。

let t = frameCount*0.01;

これは、何をしているかというと、draw関数が呼び出されるごとに、少しづつ増えていく量を定義している。
これを三角関数の、位相の部分に足してやると、円が動き出す。

 circle(200*Math.cos(i*Math.PI*2/100 + t),200*Math.sin(i*Math.PI*2/100 + t),100);

この状態で、この動いている円をコントロールするパラメーターを導入しよう。

slider = createSlider(0, 10, 1);
slider.position(10, 30);
slider.style('width', '800px');

let param = slider.value();

これは何をしているかというと、パラメーターをスライダーを通してコントロールできるようにしている。
スライダーというのは、マウスで動かせるメーターのようなもので、今の場合、0~10までの値を取れるようにした。
そして、このparamをコサインの位相の中に、次のように書く。

 circle(200*Math.cos(i*param*Math.PI*2/100 + t),200*Math.sin(i*Math.PI*2/100 + t),100);

このようにすることで、動いている円を、スライダーの動きによってコントロールできる。
コード全体は、以下の通り。

main.js

let cx;
let cy;
let W;
let H;


function setup() {
  createCanvas(windowWidth, windowHeight);
  background(100);
  cx = windowWidth / 2;
  cy = windowHeight / 2;
  W = windowWidth;
  H = windowHeight;

  slider = createSlider(0, 10, 1);
  slider.position(10, 30);
  slider.style('width', '800px');

}

function draw() {
  background(100);


  noFill();
  translate(cx,cy);

  for(let i=0;i<100;i++){

    let t = frameCount * 0.01;
    let param = slider.value();

    //line(200*Math.cos(i*param*Math.PI*2/100 + t),200*Math.sin(i*Math.PI*2/100 + t),200*Math.cos((i+1)*param*Math.PI*2/100 + t),200*Math.sin((i+1)*Math.PI*2/100 + t))

    stroke(250,0,250);
    circle(200*Math.cos(i*param*Math.PI*2/100 + t),200*Math.sin(i*Math.PI*2/100 + t),100/(param+1));

  }


}



これで、とりあえずのインタラクションは完成。コメントアウトしてあるラインの部分を入れたり、色々と遊べる要素はある。
色々と工夫して楽しもう。
以下にデモを置いた。それではまた。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1