example:
https://processing.org/examples/arrayobjects.html
Exercise:
1.
change 1-dimension array into 2-dimension
Module [] mods; v.s. Module[][] mods;
2. change objects into 3D
3. Change update() to respond to mouseX, mouseY
Sample codes for 2D array of objects
---------------------------------------------------------
int unit = 40;
int count;
int wideCount;
int highCount;
Module[][] mods;
void setup() {
size(640, 360, P3D);
lights();
//noStroke();
wideCount = width / unit;
highCount = height / unit;
//count = wideCount * highCount;
mods = new Module[highCount][wideCount];
// int index = 0;
for (int y = 0; y < highCount; y++) {
for (int x = 0; x < wideCount; x++) {
mods[y][x] = new Module(x*unit, y*unit, unit/2, unit/2, random(0.05, 0.8), unit);
}
}
}
void draw() {
background(0);
for (int y = 0; y < highCount; y++) {
for (int x = 0; x < wideCount; x++) {
mods[y][x].update();
mods[y][x].display();
}
}
/* for (Module mod : mods) {
mod.update();
mod.display();
}
*/
}
class Module {
int xOffset;
int yOffset;
float x, y;
int unit;
int xDirection = 1;
int yDirection = 1;
float speed;
// Contructor
Module(int xOffsetTemp, int yOffsetTemp, int xTemp, int yTemp, float speedTemp, int tempUnit) {
xOffset = xOffsetTemp;
yOffset = yOffsetTemp;
x = xTemp;
y = yTemp;
speed = speedTemp;
unit = tempUnit;
}
// Custom method for updating the variables
void update() {
}
// Custom method for drawing the object
void display() {
fill(255);
ellipse(xOffset + x, yOffset + y, 6, 6);
pushMatrix();
translate(xOffset, yOffset, -random(100));
rotateY(1.25);
rotateX(-0.4);
box(30);
popMatrix();
}
}
沒有留言:
張貼留言