Array with Objects

main_sketch.pde

// Object Oriented example in 3D
 
// Multiple objects can better be kept in an array
Tile[] tiles = new Tile[64];
 
void setup() {
  size (300, 300, P3D);
  noStroke();
 
  int tileSize = 32;
  int offsetLeft = 8;
  int offsetTop = 8;
  int spacerX = 4;
  int spacerY = 4;
 
  // Make a 8 x 8 grid of tiles
  int tileCounter = 0; // a counter to iterate through the array 
  for (int yPos = 0; yPos < 8; yPos++) {
    for (int xPos = 0; xPos < 8; xPos++) {
      // calculate the x and y positions of the center of the tile
      int x = tileSize / 2 + offsetLeft + ((tileSize + spacerX) * xPos);
      int y = tileSize / 2 + offsetTop + ((tileSize + spacerY) * yPos);
      tiles[tileCounter] = new Tile(x, y, tileSize);
      // increment the counter
      tileCounter++;
    }
  }
}
 
void draw() {
  background(80);
  fill(200);
 
  // Iterate through all the tiles
  for (int i = 0; i < tiles.length; i++) {
    tiles[i].checkMouse();
    tiles[i].animate();
    tiles[i].display();
  }
}

Tile.pde

class Tile {
  int x, y, wh;
  float thetaY, rotationSpeed;
 
  Tile(int centerX, int centerY, int squareSize) {
    thetaY = 0.0;
    rotationSpeed = 0.0;
    x = centerX;
    y = centerY;
    wh = squareSize;
  }
 
  void animate() {
    thetaY += rotationSpeed;
  }
 
  void display() {
    pushMatrix();
 
    translate(x,y);
    rotateY(thetaY);
    rectMode(CENTER);
    rect(0,0, wh, wh);
 
    popMatrix();
  }
 
  void checkMouse() {
    // Is the mouse within my original region?
    int h = wh / 2; // h = halfsize
    if (((mouseX > x-h) && (mouseX < x+h)) && ((mouseY > y-h) && (mouseY < y+h))) {
      // increase the rotationSpeed
      rotationSpeed += 0.02;
    } else {
      // if not, decrease the rotationSpeed (less than the increase)
      rotationSpeed -= 0.002;
      // but not make the rotationSpeed less than 0
      if (rotationSpeed < 0) {
        rotationSpeed = 0;
      }
    }
  }
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License