Particles within borders of an ellipse p5.js

309 Views Asked by At

I'm new to particles and I have the basic particle system set up.

I want them to stay within the borders of an ellipse. Is that possible? because I can't find it anywhere online.

let particles = [];

function setup(){
  createCanvas(600,400);
}

function draw(){
  background(0);
  //how many new articles to add per frame (now it's 5)
  for(let i=0; i<5;i++){
    let p = new Particle();
    //push will add a new Particle to the array of particles
    particles.push(p);
  }
  //backwards through the array because otherwise the particles will turn on and off because of the finished()
  //this will also keep the same amount of particles in the sketch.
  for(let i = particles.length-1; i>=0; i--){
    particles[i].update();
    particles[i].show();
    if(particles[i].finished()){
      //splice removes this particle from the array on position i.
      particles.splice(i,1);
    }
  }
}

class Particle {
  constructor(){
    //Want the particles to start at the bottom
    this.x = 300;
    this.y = 380;
    // random velocity
    this.vx = random(-1,1);
    //random velocity upwards
    this.vy = random(-5, -1);
    //give particles transparancy
    this.alpha = 255;
  }

  update(){
    //change the location to some random amount
    this.x += this.vx;
    this.y += this.vy;
    //it will lose some alpha with each frame
    this.alpha-=5;
  }

  finished(){
    //see if the alpha became 0 or less, then return true or false.
    return this.alpha < 0;
  }

  show() {
    noStroke();
    // stroke(255);
    fill(255, this.alpha);
    //here you can load images which will create a more interesting visual effect
    ellipse(this.x, this.y,16,16);
  }
}

I want to learn how to create a similar effect as the second sketch on here https://www.patrik-huebner.com/ideas/ex8/ the number 8 (it starts as one particle and then bursts into multiple.) I don't want to copy the work, just learn how it works because of personal interest.

1

There are 1 best solutions below

0
Jacob Stuligross On

If you want the particles to disappear when they leave the circle, you can put that into the update() method with an if statement:

update(){
  if (dist(startPoint.x, startPoint.y, this.x, this.y) > radius) {
    this.alpha = 0;
  }
  ...
}

The finished() method will take care of removing them from the array.

If you just want them to stop once they reach the edge (which has a pretty similar effect), you can change the update() method so that it only moves the particles if they are within the proper radius:

update(){
  if (dist(startPoint.x, startPoint.y, this.x, this.y) < radius) {
    //change the location to some random amount
    this.x += this.vx;
    this.y += this.vy;
  }
  //it will lose some alpha with each frame
  this.alpha-=5;
}