Skip to content

Instantly share code, notes, and snippets.

@KrabCode
Created December 25, 2024 10:52
Show Gist options
  • Save KrabCode/c15be8163139b04a3f49e048273107a9 to your computer and use it in GitHub Desktop.
Save KrabCode/c15be8163139b04a3f49e048273107a9 to your computer and use it in GitHub Desktop.
Demonstrating adding up various forces as acceleration of a single particle.
PVector emitter = new PVector();
int particleCount = 100;
int particlesCreatedPerFrame = 5;
int particleLifetimeFrames = 60;
float time;
ArrayList<Particle> particles = new ArrayList<Particle>();
void setup() {
size(800, 800);
background(24);
emitter.x = width/2;
emitter.y = height/2;
}
void draw() {
time = radians(frameCount);
blendMode(SUBTRACT);
fill(5); // fade to gray
noStroke();
rect(0, 0, width, height);
blendMode(LIGHTEST);
fill(24); // enforce minimum gray
rect(0, 0, width, height);
blendMode(BLEND);
fill(255);
ellipse(emitter.x, emitter.y, 10, 10);
updateParticles();
}
void updateParticles() {
ArrayList<Particle> particlesToRemove = new ArrayList<Particle>();
for (int i = 0; i < particlesCreatedPerFrame; i++) {
particles.add(new Particle());
}
for (Particle p : particles) {
if (p.isDead()) {
particlesToRemove.add(p);
}
p.update();
p.draw();
}
particles.removeAll(particlesToRemove);
}
void mouseMoved() {
emitter.x = mouseX;
emitter.y = mouseY;
}
class Particle {
int lifeStarted = frameCount;
int startRandomMag = 5;
PVector spd;
PVector pos;
int size = 2;
Particle() {
pos = emitter.copy();
spd = PVector.random2D().setMag(startRandomMag);
}
void update() {
PVector acc = getCurrentForces();
spd.add(acc);
spd.mult(0.95f);
pos.add(spd);
}
void draw() {
ellipse(pos.x, pos.y, size, size);
}
float lifeNorm() {
return constrain(norm(frameCount, lifeStarted, lifeStarted + particleLifetimeFrames), 0, 1);
}
boolean isDead() {
return lifeNorm() >= 1;
}
PVector getCurrentForces() {
float returnForceMag = 1;
float noiseMag = 0.5;
float noiseFreq = 10.5;
float noiseTimeSpeed = 2;
PVector towardsEmitter = PVector.sub(emitter, pos).normalize().setMag(returnForceMag * lifeNorm());
PVector noise = new PVector(-1+2*noise(pos.x*noiseFreq, pos.y*noiseFreq, noiseTimeSpeed * time),
-1+2*noise(pos.x*noiseFreq, pos.y*noiseFreq, noiseTimeSpeed * time + 332)
).setMag(noiseMag);
PVector forces = new PVector();
forces.add(towardsEmitter);
forces.add(noise);
return forces;
}
}
@KrabCode
Copy link
Author

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment