简体   繁体   English

每500帧从ArrayList中移除元素

[英]Removing element from ArrayList every 500 frames

I have this arraylist: 我有这个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? 如何构造该语句,以便每500帧删除predators数组列表中的最后一个元素? Does it need a loop of some sort? 是否需要某种循环?

if (frameCount == 500){
 predators.remove(1)
}

If you already have a variable that keeps track of what frame you are on, you can use this if statement: 如果您已经有了一个变量,可以跟踪所处的帧,则可以使用以下if语句:

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. 由于您使用1作为ArrayList的remove方法的参数,因此我也这样做了,但是请注意,由于arrayList索引从0开始计数,因此它将始终删除arrayList中的第二个对象。

This will only run every time the framecount is a multiple of 500. 仅在帧数是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. 如果尚未跟踪frameCount,则必须将frameCount++放入每个帧执行的循环中。

The draw() function is called 60 times per second, so that's the loop you would be using. draw()函数每秒被调用60次,所以这就是您要使用的循环。 The frameCount variable is incremented automatically each time draw() is called. 每次调用draw()时, frameCount变量都会自动增加。

Like The Coding Wombat said, you can use the modulo operator to determine when a variable (like frameCount ) is a multiple of a value (like 500 ). 就像The Coding Wombat所说的那样,您可以使用模运算符来确定变量(例如frameCountframeCount是值的倍数(例如500 )。

You can combine those ideas to do something once ever 500 frames: 您可以将这些构想结合起来,一次完成500帧:

ArrayList<Creature> predators = new ArrayList<Creature>();

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

void draw(){
  if (frameCount % 500 == 0){
   predators.remove(predators.size()-1);
  }

  //draw your frame
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM