%
割り算した余りを求める
//countを4で割ったあまりが0のとき
if (count % 4 == 0) {
drawRect(); //四角
}
//countを4で割ったあまりが2のとき
if (count % 4 == 2) {
drawEllipse(); //円
}
//countを1ずつ増加
count ++;
変数counは、1ずつ増加します。
そのcountを4で割ると、余りは0〜3まで変化します。
0÷4 = 0...0
1÷4 = 0...1
2÷4 = 0...2
3÷4 = 0...3
4÷4 = 1...0
4÷4 = 1...1
6÷4 = 1...2
7÷4 = 1...3
四角と円を交互に描くプログラムです。
//一定時間おきに、
//四角と円を交互に
//ランダムに図形を描く
//変数
let timestamp = 0;
let count = 0;
function setup() {
//画面サイズ
createCanvas(500, 500);
//背景を塗る
background(200, 220, 220);
}
function draw() {
//250ミリ秒おきに
if (millis() - timestamp > 250) {
timestamp = millis();
//countを4で割ったあまりが0のとき
if (count % 4 == 0) {
drawRect(); //四角
}
//countを4で割ったあまりが2のとき
if (count % 4 == 2) {
drawEllipse(); //円
}
//countを1ずつ増加
count ++;
}
}
//四角を描く
function drawRect() {
//線をナシ
noStroke();
//塗り色
fill(random(100, 200), random(100, 200), random(10, 25), 50);
//四角の基準点を中心に
rectMode(CENTER);
//四角を描く
rect(random(0, 500), random(0, 500), random(0, 500), random(0, 500));
}
//円を描く
function drawEllipse() {
//線をナシ
noStroke();
//塗り色
fill(random(200, 255), 50, random(10, 250), 50);
//円を描く
ellipse(random(0, 500), random(0, 500), random(0, 500), random(0, 500));
}
%で任意の数で割った余りをもとめることで、「何個おきに〇〇する」というプログラムができる。