Processing与粒子系统的实现

2019-03-10  本文已影响0人  147d858e3063

ParticleSystem ps;

PShape s;

float angle=0;

float aVelocity=0;

float aAcceleration=0.001;

void setup() {

  size(240, 860);

  ps = new ParticleSystem(new PVector(width/2, height-50));

}

void draw() {

  background(255);

  ps.addParticle();

  ps.run();

}

void mousePressed(){

  ps=(new ParticleSystem(new PVector(mouseX,mouseY)));

}

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(-14, -1));

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

  }

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

    rectMode(CENTER);

    pushMatrix();

  // translate(0,0);

    rotate(angle);

    float k=random(1,10);

    line(location.x-k,location.y,location.x+k,location.y);

    ellipse(location.x+k,location.y,8,8);

    ellipse(location.x-k,location.y,8,8);   

    line(location.x,location.y-k,location.x,location.y+k);

    ellipse(location.x,location.y+k,8,8);

    ellipse(location.x,location.y-k,8,8);

    s=createShape();

  s.beginShape();

  s.vertex(location.x+50/2,location.y+18/2);

  s.vertex(location.x+61/2,location.y+37/2);

  s.vertex(location.x+83/2,location.y+43/2);

  s.vertex(location.x+69/2,location.y+60/2);

  s.vertex(location.x+71/2,location.y+82/2);

  s.vertex(location.x+50/2,location.y+73/2);

  s.vertex(location.x+29/2,location.y+82/2);

  s.vertex(location.x+31/2,location.y+60/2);

  s.vertex(location.x+17/2,location.y+43/2);

  s.vertex(location.x+39/2,location.y+37/2);

  s.endShape();

    shape(s);

    popMatrix();

    // draw circle

    //float k=10;

  // ellipse(location.x, location.y, k, k);

  }

}

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

      }

    }

  }

}

上一篇 下一篇

猜你喜欢

热点阅读