Search code examples
processing

How to repeat pattern in Processing


I have the following code. I am trying to use TRANSLATE to move down the Y position on each loop pass, but it doesn't honor the Y position as indicated in the variable. Suggestions?

int vShapePosX = 0;
int vShapePosY = 0;

int[] myVertX = { ... };
int[] myVertY = { ... };

void draw() {
    int j = 0;
    while (j < 10) {
        fDrawRow();
        translate(vShapePosX, vShapePosY);
        vShapePosY = vShapePosY + 100;
        println(j);
        j = j + 1;
    }
    stop();
}
        
void fDrawRow(){
    int i = 0;
    while (i < 24) {
        // -------------- START -- DRAW SHAPE
        beginShape();
        int vCount = 0;
        while (vCount < 24) {
            vertex(myVertX[vCount], myVertY[vCount]);
            myVertX[vCount] = myVertX[vCount] + 85;     
            vCount++;                                   
        }
        endShape();
        // -------------- END -- DRAW SHAPE
        i = i + 1;
    } // end WHILE loop
} // end function

Solution

  • translate() does not set a translation matrix. It constructs a new translation matrix and and multiplies the current matrix by the new matrix. Thus you have to save the current matrix by pushMatrix() before you apply the translation and you have to restore the matrix by popMatrix() after drawing the object.
    Furthermore, I suggest to use a for-loop and to reset the variable vShapePosY before the loop:

    void draw() {
        
        vShapePosY = 0;
        for (int j = 0; j < 10; j++) {
    
            pushMatrix(); // <--- save current matrix
    
            translate(vShapePosX, vShapePosY); // <--- change current matrix 
            fDrawRow();
    
            popMatrix(); // <--- restore current matrix 
            
            vShapePosY = vShapePosY + 100;
        }
        stop();
    }
    

    Another approach is to gradually change the translation by (0, 100) in the loop:

    void draw() {
    
        translate(vShapePosX, vShapePosY);
    
        pushMatrix();
        for (int j = 0; j < 10; j++) { 
            fDrawRow();
            translate(0, 100); // <--- change current matrix 
        }
        popMatrix();
    
        stop();
    }