javaarraylistprocessingboids

Modifying ArrayList object values from another class


I have two classes: class Creature which contains ArrayList boids, and class Food. Boids have a few parameters:

 Creature(float posX, float posY, int t, int bth, int ah) {
    location = new PVector(posX, posY);
    vel = new PVector(random(-5,5), random(-5, 5));
    acc = new PVector();
    type = t;
    if (t == 1) { btype = bth; }
    else { health = bth; }
    if (t == 1) { age = ah; }
    else { hunger = ah; }
    wdelta = 0.0;
    action = 0;
    if (btype == 1) { mass = 5.0; }
    else { mass = 7.0; }
  }

Food class has this method:

  void foodtime(ArrayList boids) {
    for (int i = 0; i < boids.size(); i++) {
      Creature boid = (Creature) boids.get(i);
      float distance = PVector.dist(location, boid.location);
      if (distance < 0.5) {
        bnumadj = i;
        count++;
        if (count == quantity) {
          planet.food.remove(this);
          count = 0;
          bnumadj = -1;
        }
      }
    }
  }

What I'm trying to achieve is that if a boid "eats" the food, their boid type (btype) changes from 2 to 1.

I'm trying to use bnumadj variable to feed it back to the boid in this method:

  void boid(ArrayList boids) {
    for (int i = 0; i < boids.size(); i++) {
      if (i == bnumadj) {
        this.btype = 1;
        bnumadj = -1;
      }
    }
  }

Where am I going wrong?


Solution

  • This seems like a very convoluted way to do this, so I'm not surprised you're having issues. You're comparing values to indexes, which doesn't make a ton of sense to me.

    Instead, try using a simple nested loop to do what you want. You can use an Iterator to make it easier to remove items while iterating.

    ArrayList<Creature> boids = new ArrayList<Creature>();
    ArrayList<Food> food = new ArrayList<Food>();
    //populate ArrayLists
    
    void draw(){
    
       for(Creature boid : boids){
          Iterator<Food> foodIter = food.iterator();
    
          while(foodIter.hasNext()){
             Food f = foodIter.next();
             float distance = PVector.dist(boid.location, food.location);
             if (distance < 0.5) {
                boid.btype = 1;
                foodIter.remove(); //removes the food
            }
          }
    
       }
    
       //draw the scene
    }
    

    I suppose you could move the second iteration using the Iterator inside the Creature type, but the basic idea is this: keep it simple by using an Iterator to remove the Food instead of trying to match indexes.