Drawing with Emitters | Creative Coding with Processing.js for Windows 8 JavaScript applications

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
See emitters sketch in action
We build upon the principles learned so far and create an interactive particle emitter you can use to draw on the stage. We also look at reusing a fixed collection of elements and dynamically managing their life cycle.
To follow along in Visual Studio, please download the Processing Sketchbook projection.
The finished sketch for this lesson can be found below:

int totalParticles = 100;
Particle[] particles = new Particle[totalParticles];
float targetX = 0.0;
float targetY = 0.0;
int particleIndex = 0;
int width, height;

void setup() {
width = 500;
height = 550;
size(width, height);
noStroke();
smooth();
background(0);
for (int i = 0; i < totalParticles; i++) {
Particle particle = new Particle();
particles = particle;
}
};

void draw() {
fill(color(0, 0, 0, 20));
rect(0, 0, width, height);
for (int i = 0; i < totalParticles; i++) {
particles.update();
particles.render();
}
};

void pointerMove(Pointer e) {
targetX += (e.offsetX - targetX) * .2;
targetY += (e.offsetY - targetY) * .2;
var nextParticle = particles[particleIndex];
nextParticle.reset(targetX, targetY);
if (++particleIndex >= particles.length) particleIndex = 0;
}

class Particle {
float x = 0.0;
float y = 0.0;
float vx = 0.0;
float vy = 0.0;
float r = 255;
float g = 255;
float b = 255;
float a = 255;
color pColor = color(255, 255, 255, 255);
int life = 0;

void update() {
if (this.life > 0) {
this.life--;
if (this.life < 50) {
this.x += this.vx;
this.y += this.vy;
this.vx += random(4) - 2;
this.vy += random(4) - 2;
this.vx *= .9;
this.vy *= .9;
this.a = 255 * (this.life / 50.0);
}
}
}

void reset(float _x, float _y) {
this.x = _x;
this.y = _y;
this.vx = random(4) - 2;
this.vy = random(4) * 4 - 2;
this.life = 150;
this.g = map(_x, 0, width, 0, 255);
this.b = map(_y, 0, height, 0, 255);
this.a = 255;
}

void render(){
fill(color(this.r, this.g, this.b, this.a));
ellipse(this.x, this.y, 5, 5);
}
}
17d9d8aa5414e0327f726dc9f6b6fdb8.gif


View the full article
 
Back
Top