
class Particle {
  Body body;
  color myColor;
  float w,h;
  float theta;
  float transparency;
  float transparencyVel; // depends on my type
  float gravity; // depends on my type
  int type;

  // Constructor
  Particle(int Type, float x, float y, float XVel, float YVel, float Transparency) {
    type = Type;
    w = 10;
    h = 10;
    // Add the box to the box2d world
    makeBody(new Vec2(x/WS, y/WS), w, h);
    body.setLinearVelocity(new Vec2(XVel, YVel));
    body.setAngularVelocity(random(-20,20));
    transparency = Transparency;
    // STAR particle!
    if (type == 1) {
      gravity = 0.3;
      transparencyVel = -2;
      myColor = color(random(48,68),255,220);
    }
    // GENERIC particle!
    else {
      gravity = 0.5;
      transparencyVel = -0.5;
      myColor = color(random(0,255),160,255);
    }
  }

  // This function removes the particle from the box2d world
  void killBody() {
    box2d.destroyBody(body);
  }

  // Is the particle ready for deletion?
  boolean done() {
    // Let's find the screen position of the particle
    Vec2 pos = box2d.getBodyPixelCoord(body);
    // Is it off the bottom of the screen?
    if (pos.y > height+w*h) {
      killBody();
      return true;
    }
    return false;
  }

  // Drawing the box
  void draw() {
    //Math.
    Vec2 pos = box2d.getBodyPixelCoord(body);
    pos.x *= WS;
    pos.y *= WS;
    theta = body.getAngle();
    body.setLinearVelocity(new Vec2(body.getLinearVelocity().x, body.getLinearVelocity().y-gravity));
    transparency += transparencyVel; //fade me out
    if (transparency < 0) { //if I'm all the way faded, remove me from the ArrayList of the Flip I belong to
      killBody();
      particles.remove(this);
    }

    //Draw.
    pushMatrix();
    //if (myAxis == 1) translateAndRotateForAxis1();
    translate(pos.x, pos.y);
    rotate(theta);
    drawBody();
    popMatrix();
  }

  void drawBody() {
    fill(myColor, transparency);
    rect(0, 0, w, h);
  }

  // This function adds the rectangle to the box2d world
  void makeBody(Vec2 center, float w_, float h_) {
    // Define a polygon (this is what we use for a rectangle)
    PolygonDef sd = new PolygonDef();
    float box2dW = box2d.scalarPixelsToWorld(w_/2)/WS;
    float box2dH = box2d.scalarPixelsToWorld(h_/2)/WS;
    sd.setAsBox(box2dW, box2dH);

    // Parameters that affect physics
    sd.density = 1.0f;
    sd.friction = 0.5f;
    sd.restitution = 0.4f;
    //Filter! (No interacting with aesthetic particles!)
    sd.filter.categoryBits = 0x0004;
    sd.filter.maskBits = 0x0002;

    // Define the body and make it from the shape
    BodyDef bd = new BodyDef();
    bd.position.set(box2d.coordPixelsToWorld(center));

    body = box2d.createBody(bd);
    body.createShape(sd);
    body.setMassFromShapes();

    // Give it some initial random velocity
    body.setLinearVelocity(new Vec2(random(-5, 5), random(2, 5)));
    body.setAngularVelocity(random(-5, 5));
  }
}
