每500帧从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); }
如何构造语句,以便每500帧移除predators
arraylist中的最后一个元素? 它需要某种循环吗?
if (frameCount == 500){ predators.remove(1) }
如果您已经有一个跟踪您所在框架的变量,则可以使用以下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 }
由于您使用1
作为ArrayList的remove方法的参数,我也这样做了,但请注意,这将始终删除arrayList中的第二个对象,因为arrayList索引从0开始计数。
这只会在每次framecount为500的倍数时运行。
如果您还没有跟踪frameCount,则必须将frameCount++
放在每帧执行的循环中。
draw()
函数每秒调用60次,这就是你要使用的循环。 每次调用draw()
时, frameCount
变量都会自动递增。
就像The Coding Wombat所说,你可以使用模运算符来确定变量(如frameCount
) frameCount
是值的倍数(如500
)。
你可以将这些想法结合起来做一次500帧的事情:
ArrayList predators = new ArrayList (); 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 }