制作生态系统时处理错误

Error on Processing when making an Ecosystem

当我无法让我的动物到达水果时,我正在做一个关于处理的生态系统,起初我试图让动物找到食物然后到达它,但它没有成功动物在屏幕上随机走动,所以在我第二次尝试时,我做了一些类似于重力吸引的事情,让水果吸引了动物,但我得到了这个错误,"ArrayIndexOutOfBoundsException: 1" 谁能找到这个的来源有问题吗?

这是第一页:

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);

  }

}

这是动物 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);

  }

}

这是水果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;

  }


}

您的问题在这里:

for(int i = 0; i < fruit.length; i++) {   

    PVector seek = fruit[i].attractAnimal(animal[i]);
    // this line and the previous for i = 1
    animal[i].gatherFood(seek);


    fruit[i].display();

  }

你有 2 个水果和 1 个动物。当您为第二只动物 I = 1 访问 animal[i] 时,您超出了数组的可用索引,导致此异常。