オブジェクトの配列で100個のキャラを管理します。103より改善されています。
p5.js oop
Learning OOP Object Oriented Programming
100個のキャラをオブジェクトの配列で管理しています。
103との比較
| 103(変数ベース) | 203(オブジェクトベース) |
|---|---|
5つの配列 x[], y[], ... |
1つの配列 objs[] |
x[i], y[i] が同じキャラか分かりにくい |
objs[i].x, objs[i].y で明確 |
改善点
const obj = {
x: random(width),
y: random(height),
xSpeed: ...,
...
};
objs.push(obj);1つのキャラ = 1つのオブジェクト。配列の管理がシンプルになりました。
オブジェクト(JSON)の価値
ここまで見てきたように、オブジェクト(JSON形式)はデータ管理において非常に優秀です。
- 関連するデータを1つにまとめられる
- 構造が明確で、可読性が高い
- APIやファイル保存など、データのやり取りにも広く使われる
この知識は、プログラミング全般で役立ちます。ぜひ覚えておいてください。
まだ残る課題
データはまとまりましたが、処理(update, display)は外部関数のまま。
データと処理を一体化させたい...そこで登場するのが「クラス」です!
View Source Code
let W, H, PW, PH;
const PADDING_RATIO = 0.2;
const MAX_SPEED = 10;
let objs = [];
const MAX = 100;
function prepare() {
for (let i = 0; i < MAX; i++) {
const obj = {
x: random(width),
y: random(height),
xSpeed: (Math.random() - 0.5) * MAX_SPEED,
ySpeed: (Math.random() - 0.5) * MAX_SPEED,
acceleration: 0.1,
};
objs.push(obj);
}
}
function update() {
for (let i = 0; i < objs.length; i++) {
const obj = objs[i];
obj.x += obj.xSpeed;
obj.y += obj.ySpeed;
if (obj.x < 0 + PW) {
obj.xSpeed += obj.acceleration;
} else if (obj.x > W - PW) {
obj.xSpeed -= obj.acceleration;
}
if (obj.y < 0 + PH) {
obj.ySpeed += obj.acceleration;
} else if (obj.y > H - PH) {
obj.ySpeed -= obj.acceleration;
}
}
}
function display() {
for (let i = 0; i < objs.length; i++) {
const obj = objs[i];
stroke(0);
fill(0);
ellipse(obj.x, obj.y, 10, 10);
// text([i + "_1:", Math.floor(obj.x), Math.floor(obj.y)], obj.x + 10, obj.y + 10);
}
}
// main
function setup() {
createCanvas((W = windowWidth), (H = windowHeight));
PW = W * PADDING_RATIO;
PH = H * PADDING_RATIO;
prepare();
}
function draw() {
background(255);
update();
display();
}