Array 2D

This example is for Processing version 1.5+. If you have a previous version, use the examples included with your software. If you see any errors or have suggestions, »please let us know.

Array Objects.

Demonstrates the syntax for creating an array of custom objects.

Updated 26 February 2010.


int unit = 40;
int count;
Module[] mods;


void setup() {
  size(320, 240);
  background(176);
  noStroke();

  int wideCount = width / unit;
  int highCount = height / unit;
  count = wideCount * highCount;
  mods = new Module[count];

  int index = 0;
  for (int y = 0; y < highCount; y++) {
    for (int x = 0; x < wideCount; x++) {
      mods[index++] = new Module(x*unit, y*unit, unit/2, unit/2, random(0.05, 0.8));
    }
  }
}


void draw() {
  for (int i = 0; i < count; i++) {
    mods[i].update();
    mods[i].draw();
  }
}




class Module {
  int mx, my;
  int big;
  float x, y;
  int xdir = 1;
  int ydir = 1;
  float speed; 
  
  // Contructor (required)
  Module(int imx, int imy, int ix, int iy, float ispeed) {
    mx = imx;
    my = imy;
    x = ix;
    y = iy;
    speed = ispeed;
    big = unit;
  }
  
  // Custom method for updating the variables
  void update() {
    x = x + (speed * xdir);
    if (x >= big || x <= 0) {
      xdir *= -1;
      x = x + (1 * xdir);
      y = y + (1 * ydir);
    }
    if (y >= big || y <= 0) {
      ydir *= -1;
      y = y + (1 * ydir);
    }
  }
  
  // Custom method for drawing the object
  void draw() {
    stroke(second() * 4);
    point(mx+x-1, my+y-1);
  }
}