We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Ive tried to adapt the "Accelerating towards the mouse" example from "The Nature of Code" to a sketch where the ellipses would gravitationally attract each other, but when I try to run it Im getting an "ArrayIndexOutOfBoundsExeption" and Im not sure why. Im still entirely new to processing and programming in general, so maybe Im missing out some basic things. I apologize for that and for my bad english. Im grateful for your advice.
Heres the code:
Mover[] mover = new Mover[5];
void setup() {
size(700, 700);
for ( int i = 0; i< mover.length; i++) {
mover[i] = new Mover();
}
}
void draw() {
for ( int i = 0; i< mover.length; i++) {
background(255);
mover[i].update();
mover[i].display();
}
}
class Mover {
PVector[] velocity = new PVector[5];
PVector[] location = new PVector[5];
PVector acceleration;
Mover () {
for ( int i = 0; i< mover.length; i++) {
location[i] = new PVector(random(width), random(height));
velocity[i] = new PVector(0, 0);
}
acceleration = new PVector(0, 0);
}
void update() {
for ( int i = 0; i< mover.length; i++) {
for ( int x = 0; x< mover.length; i++) {
PVector dir = PVector.sub(location[x], location[i]);
float g = dir.mag();
dir.normalize();
dir.div(g);
acceleration = dir;
velocity[i].add(acceleration);
location[i].add(velocity[i]);
}
}
}
void display() {
for ( int i = 0; i< mover.length; i++) {
fill(0);
noStroke();
ellipse(location[i].x, location[i].y, 15, 15);
}
}
}
Answers
The exception error is caused in line 41 which should be
for ( int x = 0; x< mover.length; x++) {
not
i++
Thank you so much. Its such a stupid mistake.
And I was missing out something basic