Rewriting a sketch using inheritance
in
Programming Questions
•
7 months ago
Hi guys, I want to rewrite a sketch (a single particle system) by using inheritance. The problem is that I don't see any variables that repeat themselves. Any suggestions?
- ParticleSystem ps;
- void setup() {
- size(800,200);
- smooth();
- ps = new ParticleSystem(new PVector(width/2,50));
- }
- void draw() {
- background(255);
- ps.addParticle();
- ps.run();
- }
- // A simple Particle class
- class Particle {
- PVector location;
- PVector velocity;
- PVector acceleration;
- float lifespan;
- Particle(PVector l) {
- acceleration = new PVector(0,0.05);
- velocity = new PVector(random(-1,1),random(-2,0));
- location = l.get();
- lifespan = 255.0;
- }
- void run() {
- update();
- display();
- }
- // Method to update location
- void update() {
- velocity.add(acceleration);
- location.add(velocity);
- lifespan -= 2.0;
- }
- // Method to display
- void display() {
- stroke(0,lifespan);
- strokeWeight(2);
- fill(127,lifespan);
- ellipse(location.x,location.y,12,12);
- }
- // Is the particle still useful?
- boolean isDead() {
- if (lifespan < 0.0) {
- return true;
- } else {
- return false;
- }
- }
- }
- // particle emitter
- class ParticleSystem {
- ArrayList<Particle> particles;
- PVector origin;//keeps track of the origin point (each particle begins at this point)
- ParticleSystem(PVector location) {
- origin = location.get();
- particles = new ArrayList<Particle>();
- }
- void addParticle() {
- particles.add(new Particle(origin));
- }
- void run() {
- Iterator<Particle> it = particles.iterator();
- while (it.hasNext()) {
- Particle p = it.next();
- p.run();
- if (p.isDead()) {
- it.remove();
- }
- }
- }
- }
1