jiajia
April 21, 2022, 8:18am
1
<
ArrayList particles;
void setup(){
size(200,200);
particles = new ArrayList();
}
void draw(){
background(255);
particles.add(new Particle(new PVector(width/2,50)));
Iterator it = particles.iterator();
while(it.hasNext()){
Particle p = it.next();
p.run();
if(p.isDead()){
it.remove();
}
}
}
class Particle{
PVector location;
PVector velocity;
PVector acceleration;
float lifespan;
Particle(PVector l){
acceleration = new PVector(0,0.05);
velocity = new PVector(random(-1,1),random(-2,0));
location = l.copy();
lifespan = 255.0;
}
void run(){
update();
display();
}
void update(){
velocity.add(acceleration);
location.add(velocity);
lifespan -= 2.0;
}
void display(){
stroke(0,lifespan);
fill(0,lifespan);
ellipse(location.x,location.y,8,8);
}
boolean isDead(){
if(lifespan < 0.0){
return true;
}else{
return false;
}
}
}
glv
April 21, 2022, 10:35am
2
Hello,
Please follow these instructions as a courtesy to this community:
https://discourse.processing.org/faq#format-your-code
I have come across this example before and was able to correct it with some research.
Processing 4.0b7 shows this console message:
After you add the import you will get this error:
A search in this forum for that line 23 (above picture) will find a topic that will give you some insight.
The steps I took worked to resolve this issue:
:)
2 Likes
As @glv ’s already pointed out, you need to import the Iterator interface before using it:
import java.util.Iterator;
Alternatively you can use a regular for ( ; ; )
loop, but making sure to decrease its iterator variable each time you invoke method remove() :
for (int i = 0; i < particles.size(); ++i) {
final Particle p = particles.get(i);
p.run();
if (p.isDead()) particles.remove(i--);
}
It’s even simpler if you iterate it backwards, so you don’t have to worry about decreasing the iterator for each remove() :
for (int i = particles.size(); i-- > 0; ) {
final Particle p = particles.get(i);
p.run();
if (p.isDead()) particles.remove(i);
}
For a more complex but more efficient (b/c we completely avoid container’s element left-shifting) backwards technique, see this sketch’s mousePressed() code block implementation:
4 Likes
jiajia
April 21, 2022, 2:51pm
5
OH YEA !! Very thank you for your help
2 Likes
jiajia
April 21, 2022, 2:54pm
6
I learned it with your help So THANKS!
2 Likes