line by line-grid: My sketch does not start properly

edited March 2017 in Questions about Code

Dear coders,

i want to draw a line by line-grid in Processing, but my program does not work anyway, it does not start properly, i guess it is because i try to reset x in the for-loop.

I there a good solution for that?

float y;
float a;

int cols = 16;
int rows = 50;

void setup() {
  size(540, 540);  
  noStroke();
  frameRate(10);
}

void draw() {
  background(#0000ff);
  for (float x = 0; x < width*height; x+=width/cols) {

    if (x > width) {
      y += height/rows;
      x = 0;
    }

    fill(#ff0000);

    rect(x, y, 1, 1);
  }

  // saveFrame();
}
Tagged:

Answers

  • Answer ✓

    Clarity over compactness ;)

    Kf

    float y;
    float a;
    
    int cols = 16;
    int rows = 50;
    
    void setup() {
      size(540, 540); 
      stroke(0);
      fill(#ff0000);
      frameRate(10);
    }
    
    void draw() {
      background(#0000ff);
      for (float x = 0; x < width; x+=width/cols) {
        for (float y = 0; y < height; y+=height/rows) {      
          rect(x, y, 5, 5);
        }
      }
    }
    
  • edited March 2017 Answer ✓

    you need another for-loop variable than x

    (you shouldn't manipulate the for-loop variable in most cases)

    float y=0;
    //float a;
    
    int cols = 16;
    int rows = 50;
    
    void setup() {
      size(540, 540);  
      //  noStroke();
      noFill();
    
      // frameRate(10);
    }
    
    void draw() {
    
      //  background(0);
    
      float x2=0;
      y=0;
      for (int i = 0; i < cols*rows; i++) {
    
        //fill(#ff0000);
        float size1=width/cols-4;
        float size2=height/rows-4;
        stroke(255);
        fill(255); 
        rect(x2, y, size1, size2);
    
        x2 += width/cols;
    
        // new line
        if (x2 > width) {
          y += height/rows;
          x2 = 0;
        }
      }
    
      // saveFrame();
    }
    
  • Great, thank you guys!

  • Answer ✓
    for (int i = 0 ; i < cols * rows ; i += 1) {
      rect((i % cols) * (width / cols), (i / cols) * (height / rows), 5, 5);
    }
    

    x is remainder of i / cols (multiplied by width of each column)

    y is the INTEGER division of i / cols (multiplied by the height of each row)

    Compactness over clarity 8)

    (but seriously, use kf's solution. much easier and, in fact, shorter than your original)

Sign In or Register to comment.