椭圆 p5.js 边界内的粒子

问题描述

我是粒子的新手,我已经设置了基本的粒子系统。

我希望它们保持在椭圆的边界内。那可能吗?因为我在网上找不到。

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);
  }
}

我想学习如何创建与此处 https://www.patrik-huebner.com/ideas/ex8/ 数字 8 上的第二个草图类似的效果(它从一个粒子开始,然后爆发为多个。)我不想复制作品,只是出于个人兴趣了解它是如何工作的。

解决方法

如果您希望粒子在离开圆时消失,您可以使用 update() 语句将其放入 if 方法中:

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

finished() 方法将负责将它们从数组中移除。

如果您只想让它们在到达边缘时停止(这具有非常相似的效果),您可以更改 update() 方法,使其仅移动处于适当半径内的粒子:

update(){
  if (dist(startPoint.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;
}