ArrayList<particle> particleList = new ArrayList(); //creates an array list to store particles (array list rather than array since amount will vary)
campfire fire; //campfire object
void setup() {
size(480, 360);
rectMode(CENTER);
noStroke();
fire = new campfire(width / 2, height - 40); //adds campire to bottom of the screen
}
void mouseDragged() {
//creates randomly colored particles when the mouse is dragged
particleList.add(new particle(mouseX, mouseY, int(random(-3, 3)),
4, int(random(255)), int(random(255)), int(random(255)))); //creates particles
}
void draw() {
background(19, 24, 98);
fill(255);
text("Drag your mouse to create random particles!", 10, 20);
fire.show();
for (int i = 0; i < particleList.size(); i++) {
particleList.get(i).show(); //shows & updates all the particles
if (particleList.get(i).life <= 0) {
particleList.remove(i); //removes a particle once it's "life" hits zero
}
}
}
class particle {
PVector position, velocity; //particle position & velocity stored in vectors
int dir, radius, r, g ,b; //variables for direction, radius and RGB values (for colour)
int life = (int) random(75, 100); //life variable
//particle constructor
particle(float tmpx, float tmpy, int tmpdir, int tmpradius, int tmpr, int tmpg, int tmpb) {
//instantiation of all variables
position = new PVector(tmpx, tmpy);
r = tmpr;g = tmpg;b = tmpb;
dir = tmpdir; // -1 = left, 1 = right, -2 = up, 2 = down
if (dir == 0) {
dir = floor(random(-1, -2)); //insures no particle has no direction
}
radius = tmpradius;
velocity = new PVector (0, 0);
}
void show() {
updatePosition();
life--;
fill(r, g, b);
rect(position.x, position.y, radius, radius);
}
void updatePosition() {
//moves particle based on direction with slight offsets to look less linear
if (dir % 2 != 0) {
velocity.x = dir + random(-0.5, 0.5);
velocity.y = random(-2, 2);
}
if (dir % 2 == 0) {
velocity.y = dir / 2 + random(-0.5, 0.5);
velocity.x = random(-2, 2);
}
position.add(velocity); //adds velocity vector to position vector
}
}
class campfire {
PVector position;
//campfire constructor
campfire(float tmpx, float tmpy) {
position = new PVector(tmpx, tmpy);
}
void show() {
//draws and rotates the "logs"
pushMatrix();
translate(position.x, position.y);
rotate(radians(90));
fill(70, 40, 10);
rect(0, 0, 80, 20);
rotate(radians(45));
fill(80, 70, 10);
rect(0, 0, 80, 20);
rotate(radians(-90));
fill(90, 60, 10);
rect(0, 0, 80, 20);
popMatrix();
fill(90);
rect(position.x, position.y + 30, 80, 30);
//creates the fire particles
particleList.add(new particle(position.x + random(-20, 20), position.y + random(-10, 10), -2, 4, int(random(200, 250)), 140, 45));
}
}