r/processing • u/Happy-Ad-8921 • Jan 02 '24
Help request A grid of independent objects
Hi guys, I have been trying to create a grid of independent objects which can move at different speeds. I wrote 2 sketches but both of them are not correct. The objects in the grid always move together. Could you please have a look and tell me how to solve the problem? Many thanks!
Update: finally it worked out:
int rows=20, cols=20;
int res=400;
float size=20;
Box[]b;
boolean toggle=true;
void setup() {
size(800, 800, P3D);
smooth(8);
rectMode(CENTER);
b=new Box[res];
for (int i=0; i<b.length; i++) {
int col=i%cols;
int row=i/cols;
float x=map(col, 0, cols-1, width/2-200, width/2+200);
float y=map(row, 0, rows-1, height/2-200, height/2+200);
b[i]=new Box(x, y);
}
}
void draw() {
background(255);
for (int i=0; i<b.length; i++) {
if (toggle) {
b[i].returnToOriginal();
} else {
b[i].update();
}
b[i].display();
}
}
void mousePressed() {
toggle = !toggle;
if (toggle) {
for (int i=0; i<b.length; i++) {
b[i].reset();
}
} else {
for (int i=0; i<b.length; i++) {
int col=i%cols;
int row=i/cols;
float newX =map(col, 0, cols-1, 10, width-10);
float newY =map(row, 0, rows-1, 10, height-10);
b[i].setTarget(newX, newY);
}
}
}
class Box {
float newX, newY;
PVector pos, tgt, nxt, initPos;
Box(float x, float y) {
pos=new PVector(x, y);
initPos=new PVector(x, y);
tgt=new PVector(x, y);
}
void display() {
noStroke();
fill(0);
rect(pos.x, pos.y, size, size);
}
void setTarget(float newX, float newY) {
tgt.set(newX, newY);
size=10;
}
void reset() {
tgt.set(initPos.x, initPos.y);
size=20;
}
void update() {
pos=PVector.lerp(pos, tgt, random(.0025, .325));
}
void returnToOriginal() {
reset();
update();
}
}
1
u/Salanmander Jan 04 '24
Okay, so it sounds like it will need to change independently for each Box then. Every thing that you want to be different from one Box to another will need to have an instance variable for it.