xxxxxxxxxx
//https://www.openprocessing.org/sketch/147268
final int MAX_PARTICLES = 20;
final int MAX_SIZE = 48;
final int PARTICLE_RADIUS = 4;
ArrayList<Particle> particles = new ArrayList<Particle>();
void setup()
{
size(600, 500, P2D);
for (int x = 0; x < MAX_PARTICLES; x++) {
particles.add(new Particle());
}
noStroke();
}
void draw()
{
Particle p1, p2;
fill(255, 20);
rect(0, 0, width, height);
fill(0);
//background(255);
// Draw particles
for (Particle part : particles) {
if (!part.consumed) {
part.move();
part.display();
}
}
// Search for collisions
for (int i = 0; i < particles.size(); i++) {
p1 = particles.get(i);
if (p1.consumed) {
continue;
}
for (int j = i + 1; j < particles.size(); j++) {
p2 = particles.get(j);
if (p2.consumed) {
continue;
}
float d = PVector.dist(p1.pos, p2.pos);
if (p1.size < MAX_SIZE && p2.size < MAX_SIZE) {
if (d > 0 && d < p1.size) { // Colision
if (p1.size > p2.size) {
p2.consumed = true;
p1.size = p1.size + p2.size;
} else {
p1.consumed = true;
p2.size = p2.size + p1.size;
}
}
}
}
}
}
class Particle
{
final static float BOUNCE = -1;
final static float MAX_SPEED = 2.0;
Boolean consumed = false;
int size = 4;
PVector speed = new PVector(random(-MAX_SPEED, MAX_SPEED), random(-MAX_SPEED, MAX_SPEED));
PVector pos;
ColourGenerator colour = new ColourGenerator();
Particle()
{
// Start at random location
pos = new PVector (random(width), random(height));
}
public void move()
{
// Apply our speed vector
pos.add(speed);
// Boundary heck
if (pos.x < 0)
{
pos.x = 0;
speed.x *= BOUNCE;
}
else if (pos.x > width)
{
pos.x = width;
speed.x *= BOUNCE;
}
if (pos.y < 0)
{
pos.y = 0;
speed.y *= BOUNCE;
}
else if (pos.y > height)
{
pos.y = height;
speed.y *= BOUNCE;
}
}
public void display()
{
colour.update();
noFill();
fill(colour.R, colour.G, colour.B);
ellipse(pos.x, pos.y, size, size);
}
}
class ColourGenerator
{
final static float MIN_SPEED = 0.7;
final static float MAX_SPEED = 1.5;
float R, G, B;
float Rspeed, Gspeed, Bspeed;
ColourGenerator()
{
init();
}
public void init()
{
// Random starting colour
R = random(255);
G = random(255);
B = random(255);
// Random transition
Rspeed = (random(1) > 0.5 ? 1 : -1) * random(MIN_SPEED, MAX_SPEED);
Gspeed = (random(1) > 0.5 ? 1 : -1) * random(MIN_SPEED, MAX_SPEED);
Bspeed = (random(1) > 0.5 ? 1 : -1) * random(MIN_SPEED, MAX_SPEED);
}
public void update()
{
// Random transition (keep within RGB colour range)
Rspeed = ((R += Rspeed) > 255 || (R < 0)) ? -Rspeed : Rspeed;
Gspeed = ((G += Gspeed) > 255 || (G < 0)) ? -Gspeed : Gspeed;
Bspeed = ((B += Bspeed) > 255 || (B < 0)) ? -Bspeed : Bspeed;
}
}