103.変数ベースの配列(CRAZY)

配列を使って100個のキャラを管理しますが、変数の管理が煩雑になります。

p5.js oop
Learning OOP Object Oriented Programming

100個のキャラを管理するために、配列を使っています。

一応動くけど...

let x = [];
let y = [];
let xSpeed = [];
let ySpeed = [];
let acceleration = [];

配列を使えば100個でも1000個でも対応できます。しかし...

問題点: 変数のバラバラ管理

  • 1つのキャラの情報が5つの異なる配列に分散
  • x[i], y[i], xSpeed[i] が同じキャラを指していることが分かりにくい
  • 新しいプロパティを追加するたびに、新しい配列が必要
  • 関連するデータが「まとまり」として認識しづらい

でも、その前に...もっと地獄のような例を見てみましょう。

次の104では、この状態で2種類のキャラを管理しようとします。覚悟してください。

View Source Code

let W, H, PW, PH;
const PADDING_RATIO = 0.2;
const MAX_SPEED = 10;

let x = [];
let y = [];
let xSpeed = [];
let ySpeed = [];
let acceleration = [];

let MAX = 100;

function prepare() {
  for (let i = 0; i < MAX; i++) {
    x[i] = random(W);
    y[i] = random(H);
    xSpeed[i] = (Math.random() - 0.5) * MAX_SPEED;
    ySpeed[i] = (Math.random() - 0.5) * MAX_SPEED;
    acceleration[i] = 0.1;
  }
}

function update() {
  for (let i = 0; i < MAX; i++) {
    x[i] += xSpeed[i];
    y[i] += ySpeed[i];

    if (x[i] < 0 + PW) {
      xSpeed[i] += acceleration[i];
    } else if (x[i] > W - PW) {
      xSpeed[i] -= acceleration[i];
    }

    if (y[i] < 0 + PH) {
      ySpeed[i] += acceleration[i];
    } else if (y[i] > H - PH) {
      ySpeed[i] -= acceleration[i];
    }
  }
}

function display() {
  for (let i = 0; i < MAX; i++) {
    stroke(0);
    fill(0);
    ellipse(x[i], y[i], 10);
    text([i + ":", Math.floor(x[i]), Math.floor(y[i])], x[i] + 10, y[i] + 10);
  }
}

// main

function setup() {
  createCanvas((W = windowWidth), (H = windowHeight));
  PW = W * PADDING_RATIO;
  PH = H * PADDING_RATIO;

  prepare();
}

function draw() {
  background(255);

  update();
  display();
}