1

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?

1 Answers1

1

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)))

George Profenza
  • 50,687
  • 19
  • 144
  • 218
  • Doing it like this does work! But My guess is that it fills the screen and the 3 other quadrants that we can't see due to the rotation. From what I tried here, as it will slowly fill the screen with tiles. But for my needs this is more than enough, thanks! – Miguel Henrique Salviatti Nov 14 '22 at 15:19
  • 1
    Happy to hear it helps! I don't know the size your tiles, guessing 100x100 px ? If so, you have a 12 x 12 grid, filling 1200x1200 total on a sketch that is 1200x800. You could make your sketch 1200x1200 (or `j < 8` ?). Have fun! – George Profenza Nov 14 '22 at 16:19