Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have this arraylist:

// Add predators
predators = new ArrayList();
for (int i = 0; i < predNum; i++) {
  Creature predator = new Creature(random(width), random(height), 2);
  predators.add(predator);
}

How can the statement be structured so that the last element from the predators arraylist is removed every 500 frames? Does it need a loop of some sort?

if (frameCount == 500){
 predators.remove(1)
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
185 views
Welcome To Ask or Share your Answers For Others

1 Answer

If you already have a variable that keeps track of what frame you are on, you can use this if statement:

if (frameCount % 500 == 0) {
   predators.remove(1); //use this if you want to remove whatever is at index 1 every 500 frames
   predators.remove(predators.size() -1); //use this if you want to remove the last item in the ArrayList
}

Since you used 1 as the argument for the remove method of the ArrayList, I did too, but note that this will always remove the 2nd object in the arrayList since arrayList indices start counting at 0.

This will only run every time the framecount is a multiple of 500.

If you do not already keep track of the frameCount you will have to put frameCount++ in the loop that is executed every frame.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...