Using User Defined Class in an Array

edited March 2015 in Questions about Code

I am trying to create an array out of a Class that I made. The code is for a Mover object is modified from The Nature of Code site.

I have tried several different versions of this in order to get several of my Mover objects into an array but I can't figure out the initialization of it.

Also, once I get it working is there a way to call mover.update() instead of mover[i].update?

Also, I'm using this in Processing.js

Mover[] mover;

void setup() {
  size(640,360);
  mover = new Mover[3];
}

void draw() {
  background(255);

  mover[0].update();
  mover[1].update();
  mover[0].checkEdges();
  mover[1].checkEdges();
  mover[0].display();
  mover[1].display();
}

class Mover {

  PVector location;
  PVector velocity;

  Mover() {
    location = new PVector(random(width),random(height));
    velocity = new PVector(random(-2,2),random(-2,2));
  }

  void update() {
    location.add(velocity);
  }

  void display() {
    stroke(0);
    fill(175);
    ellipse(location.x,location.y,16,16);
  }

  void checkEdges() {
    if (location.x > width) {
      location.x = 0;
    } else if (location.x < 0) {
      location.x = width;
    }

    if (location.y > height) {
      location.y = 0;
    } else if (location.y < 0) {
      location.y = height;
    }
  }
}
Tagged:

Answers

  • edited March 2015

    You create space for three Movers, but never create any Movers in those spaces. You need a line like mover[0] = new Mover();

  • Worked perfectly, thanks!

Sign In or Register to comment.