Search code examples
processing

How can I make a grid of tiles (that can be rotated randomly) in processing?


I have the following code in Processing that will produce a grid of randomly selected tiles from loaded files:

static int img_count = 6;

PImage[] img;

void setup() {
  size(1200, 800);
  img = new PImage[img_count];
  for (int i = 0; i < img_count; i++) {
    img[i] = loadImage("./1x/Artboard " + (i+1) + ".png");
  }
}

void draw() {
  for (int i = 0; i < 12; i++) {
    for (int j = 0; j < 12; j++) {
      int rand_index = int(random(img_count));
      image(img[rand_index], 100 * i, 100 * j, 100, 100 );
    }
  }
}

By itself, it almost does what I want:

image

But I need that every tile be randomly rotated as well, so I tried this:

void draw() {
  for (int i = 0; i < 12; i++) {
    for (int j = 0; j < 12; j++) {
      float r = int(random(4)) * HALF_PI;     // I added this
      rotate(r);                              // I added this
      int rand_index= int(random(img_count));
      image(img[rand_index], 100 * i, 100 * j, 100, 100 );
    }
  }
}

This second code doesn't act as I intended, as rotate() will rotate the entire image, including tiles that were already rendered. I couldn't find an appropriate way to rotate a tile the way I want, is there any way to rotate the tile before placing it?


Solution

  • You will probably need to translate before rotating. The order of transformations is important (e.g. translating, then rotating will be a different location than rotation, then translating). In your case image(img, x, y) makes it easy to miss that behind the scenes it's more like translate(x,y);image(img, 0, 0);.

    I recommend:

    void draw() {
      for (int i = 0; i < 12; i++) {
        for (int j = 0; j < 12; j++) {
          float r = int(random(4)) * HALF_PI;     // I added this
          translate(100 * i, 100 * j);            // translate first
          rotate(r);                              // I added this
          int rand_index= int(random(img_count));
          image(img[rand_index], 0, 0, 100, 100 );
        }
      }
    }
    

    (depending on your setup, you might find imageMode(CENTER); (in setup()) handy to rotate from image centre (as opposed to top left corner (default)))