[Go to “teaching” in Morimoto Lab]

Game by ball 6

動的配列について学習する。


1. Dynamic Array

It is very important and convenient.
Static array(静的配列): Until now we define an array with a fixed numbers. [static array]
Dynamic array(動的配列): However, how do you implement the below?

In such cases, we need an array with changeable numbers.

See the ArrayList that is a dynamic array in Processing.
The below code shows the difference between static array and dynamic array.

//↓ Define & new
PVector [] pos = new PVector[5];
ArrayList<PVector> po = new ArrayList<PVector>();
void setup() {
size(1000, 800);
for (int i=0; i < 5; i++) {
//↓ Second new with add
pos[i] = new PVector(i*110, 300);
po.add(new PVector(i*110, 100));
//↑★0: addの仕方について
}
noFill();
strokeWeight(5);
}
void draw() {
background(255);
//↓ Static array (green)
stroke(0,128,0);
//↓★1: .length of static array
for (int i=0; i < pos.length; i++) {
ellipse(pos[i].x, pos[i].y, 100, 100);
}
//Dynamic array (red)
stroke(255,0,0);
//↓★2: .size()
for (int i=0; i < po.size(); i++) {
//↓★3: .get()
PVector pv = po.get(i);
//↓★4: use member variables
ellipse(pv.x, pv.y, 100, 100);
//↓★5: You can do this instead of 3&4. I recommend 3&4.
//ellipse(po.get(i).x, po.get(i).y, 130, 130);
}
}
void mouseClicked() {
//↓★6
if (po.size()>0) {//if(!po.isEmpty())
//↓★7
po.remove(0);
}
print(po.size()+", " );//★See the console
}

★0: add() の引数に加えたいPVectorの変数等を指定します。
サンプルコードのやり方以外に以下のやり方がストレートです

PVector a = new PVector(100,100);
po.add(a);

が、一行増えるので、サンプルのような以下の方法が好まれます。

po.add(new PVector(100,100));

★1: length is a number of data of the static array.
★2: size() is a number of data of the dynamic array.
★3: get(i) is a method to get i’th data of the dynamic array.
★4: You can use variables (and methods) of class like this.
★5: Or you can use variables (and methods) like this.
3,4 or 5、どちらの方法でもいいのですが、個人的には3,4の方が(1行増えても)見やすい&書きやすいです。
★6: If the number of data is 0, we cannot remove the data anymore.
In order to avoid to remove when the data is nothing, we need this.
You can also use isEmpty() that returns a boolean value (true or false).
★7: remove(i) is a method to remove i’th data of the dynamic array.
Other than the above, see the official document of ArrayList (in Japanese).

Ex A. Using ArrayList, add balls at where you click.

Ex B. Using ArrayList, remove balls at where you click.

Hint: Collision detection between a mouse and ball.

Ex C. ボールクラスと動的配列を使って、ボールを増やしたり消したりするプログラムを作りなさい。

Ex D. 更にクラスにメソッドを追加し、インタラクティブに要素の数が増減することを利用した面白いアプリを作成してください。

★(ゲーム/インタラクション/ジェネラティブアート/数式/アニメーション)のいずれかの要素(複数でも)を入れてください。

下記の例は、先週と同じ例ですが、クリックしたら増える、減る+目や赤い玉がアニメーションしていますね。
これを真似してみてもいいと思います。

そういえば大阪万博のロゴマーク、「いのちの輝きくん」がTwitterで色々とアレンジされていました。
今回の課題の参考に下記のURLでぜひ遊んでみてください!