Processing 入门教程(一) 粒子系统

  • Post author:
  • Post category:其他


我的Processing 打不了中文,只能用英文注释了,很简单的代码,有不明白的留评论

开始写之前,我要吐槽一下processing,同一个项目新建一个类,只能点这个三角形新建一个标签,或者是快捷键 ctrl+shift+n,丫的,让我一顿好找

入口:

ParticleSystem ps;

void setup() {
  size(640, 360);
  ps = new ParticleSystem(new PVector(width/2, 50));
}
void draw() {

  background(0);
  ps.addParticle();
  ps.run();
}

Particle类:

class Particle {
  PVector location;
  PVector velocity;
  PVector acceleration;

  float lifespan;
  Particle(PVector l) {
    // The acceleration
    acceleration = new PVector(0, 0.05);
    // circel's x and y ==> range
    velocity = new PVector(random(-1, 1), random(-2, 0));
    // apawn's position
    location = l.copy();
    // the circle life time
    lifespan = 255.0;
  }
  void run() {
    update();
    display();
  }
  void update() {
    velocity.add(acceleration);
    location.add(velocity);
    lifespan-=1.0;
  }

  boolean isDead() {
    if (lifespan <= 0) {
      return true;
    } else {
      return false;
    }
  }
  void display() {
    // border
    stroke(0, lifespan);
    // border's weight
    strokeWeight(1);
    float r = random(0,255);
    float g = random(0,255);
    float b = random(0,255);
    // random the circle's color
    fill(r,g,b, lifespan);
    // draw circle
    ellipse(location.x, location.y, 3, 3);
  }
}

ParticleSystem管理类:

// A class to describe a group of Particles
// An ArrayList is used to manage the list of Particles 

class ParticleSystem {
  ArrayList<Particle> particles;
  PVector origin;

  ParticleSystem(PVector position) {
    origin = position.copy();
    particles = new ArrayList<Particle>();
  }

  void addParticle() {
    particles.add(new Particle(origin));
  }

  void run() {
    for (int i = particles.size()-1; i >= 0; i--) {
      Particle p = particles.get(i);
      p.run();
      if (p.isDead()) {
        particles.remove(i);
      }
    }
  }
}

效果图如下:

好心情:

âç¾å¾âçå¾çæç´¢ç»æ



版权声明:本文为qq_39097425原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。