I was doing an ecosystem on Processing when I couldn't make my animal reach the fruit, at first I was trying to make the animal find the food and then reach it, but it didn't work out as the animal was randomly walking the screen, so on my second try, I did something similar to gravitational attraction and made the fruit attract the animal, but I ended up with this error, "ArrayIndexOutOfBoundsException: 1" can anyone try to find the source of this problem?
This is the first page:
Animal[] animal = new Animal[1];
Predator predator;
Fruit[] fruit = new Fruit[2];
void setup() {
size(1536, 864);
for(int i = 0; i < animal.length; i++) {
animal[i] = new Animal();
}
predator = new Predator();
for(int i = 0; i < fruit.length; i++) {
fruit[i] = new Fruit();
}
}
void draw() {
background(60);
fill(255);
grid();
for(int i = 0; i < animal.length; i++) {
animal[i].display();
animal[i].update();
animal[i].checkEdge();
}
for(int i = 0; i < fruit.length; i++) {
PVector seek = fruit[i].attractAnimal(animal[i]);
animal[i].gatherFood(seek);
fruit[i].display();
}
}
void grid() {
strokeWeight(3);
stroke(65);
for(int i = 0; i < width; i++) {
line(70 * i, 0, 70 * i, height);
}
for(int i = 0; i < height; i++) {
line(0, 70 * i, width, 70 * i);
}
}
This is the Animal class:
class Animal {
PVector pos;
PVector vel;
PVector acc;
float mass;
Animal() {
pos = new PVector(random(0, width), random(0, height));
vel = new PVector(0, 0);
acc = new PVector(0, 0);
mass = random(5, 10);
}
void update() {
pos.add(vel);
vel.add(acc);
acc.mult(0);
}
void checkEdge() {
if(pos.x >= width || pos.x <= 0) {
vel.x = -vel.x;
}
if(pos.y >= height || pos.y <= 0) {
vel.y = -vel.y;
}
}
void gatherFood(PVector will) {
PVector w = PVector.div(will, mass);
acc.add(w);
}
void display() {
fill(255 , 150);
stroke(100);
strokeWeight(5);
ellipse(pos.x, pos.y, mass * 5, mass * 5);
}
}
This is the fruit class:
class Fruit {
PVector pos;
Fruit() {
pos = new PVector(random(0, width), random(0, height));
}
void display() {
fill(0, 185, 0);
stroke(0, 100, 0);
strokeWeight(3);
ellipse(pos.x, pos.y, 15, 15);
}
PVector attractAnimal(Animal animal) {
PVector dir = PVector.sub(pos, animal.pos);
dir.normalize();
float walk = 10 / animal.mass;
dir.mult(walk);
return dir;
}
}