【问题标题】:Particles within borders of an ellipse p5.js椭圆边界内的粒子 p5.js
【发布时间】:2021-04-24 10:12:58
【问题描述】:

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

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

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 的第二个草图类似的效果(它从一个粒子开始,然后爆发为多个。)我不想复制作品,只是学习由于个人兴趣,它是如何工作的。

【问题讨论】:

    标签: p5.js particles particle-system particles.js


    【解决方案1】:

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

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

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

    如果您只是希望它们在到达边缘后停止(效果非常相似),您可以更改 update() 方法,使其仅在粒子在适当半径内时移动:

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

    【讨论】:

      猜你喜欢
      • 2010-12-18
      • 1970-01-01
      • 1970-01-01
      • 2019-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多