Hi all! I’m fairly new to coding and all new to this forum. I have a small problem with some code which I would like a bit of guidance on. The code is supposed to model a fire/flame moving around the screen. The problem is that when the flame reaches an edge of the screen, it dies out. I want it instead to bounce of the edges, which is why I implemented the inverted velocity in the update function, but it doesn’t seem to work. The code looks like this:
class ParticleSystem {
ArrayList<Particle> particles;
PVector origin;
PVector originmove;
PImage img;
float t = 0;
float xoff;
ParticleSystem (int num, PVector v, PImage img_) {
particles = new ArrayList<Particle>();
origin = v.copy();
xoff = xoff + .05;
originmove = new PVector(noise(xoff), noise(xoff));
img = img_;
for (int i = 0; i < num; i++) {
particles.add(new Particle(origin.add(originmove), img));
particles.add(new Particle(origin, img));
}
originmove.mult(0.1);
}
void run() {
for (int i = particles.size()-1; i >= 0; i--) {
Particle p = particles.get(i);
p.run();
}
}
// Method to add a force vector to all particles currently in the system
void applyForce(PVector dir) {
// Enhanced loop!!!
for (Particle p : particles) {
p.applyForce(dir);
}
}
void addParticle() {
particles.add(new Particle(origin.add(originmove), img));
particles.add(new Particle(origin, img));
}
}
class Particle {
PVector position;
PVector velocity;
PVector acceleration;
float lifespan;
PImage img;
PImage rose;
float t = 0;
float p;
Particle(PVector l, PImage img_) {
position = l.copy();
float vx = (float) randomGaussian()*0.3;
float vy = (float) randomGaussian()*0.4 - 0.2;
velocity = new PVector(vx, vy);
acceleration = new PVector(0, 0);
lifespan = 100.0;
img = img_;
}
void run() {
update();
render();
}
void render() {
imageMode(CENTER);
tint(255, lifespan);
image(img, position.x, position.y);
}
void applyForce(PVector f) {
acceleration.add(f);
}
void update() {
position.add(velocity);
velocity.add(acceleration);
lifespan -= 2.0;
velocity.limit(2);
acceleration.mult(0);
if (position.x > width) {
velocity.mult(-1);
acceleration.mult(-1);
}
if (position.y > height) {
velocity.mult(-1);
acceleration.mult(-1);
}
}
}
ParticleSystem ps;
float t = 0;
float increment = 0.1;
void settings() {
size(640, 340);
}
void setup() {
PImage img = loadImage("blacksmoke.png");
ps = new ParticleSystem(0, new PVector(width-160, height-60), img);
background(255);
}
void draw() {
// Calculate a "wind" force based on mouse horizontal position
t += 0.6;
float dx = map(noise(t), 0, 1, -0.4, 0.5);
float dy = map(noise(t), 0, 1, -0.2, 0.1);
PVector wind = new PVector(dx, dy);
ps.applyForce(wind);
ps.run();
for (int i = 0; i < increment; i++) {
increment += 0.0001;
ps.addParticle();
}
//saveFrame("output/ps_####.png");
}
I’ve posted the three parts of the code separately; I hope that’s okay. Do you guys have any suggestions on what I’ve done wrong?
Best,
Daniel