首页 > 解决方案 > 如何在处理中重复模式

问题描述

我有以下代码。我正在尝试使用 TRANSLATE 在每个循环通道上向下移动 Y 位置,但它不尊重变量中指示的 Y 位置。建议?

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

标签: processing

解决方案


translate()不设置平移矩阵。它构造一个新的平移矩阵,并将当前矩阵乘以新矩阵。因此,您必须在应用平移之前保存当前矩阵,并且必须在绘制对象后 pushMatrix()恢复矩阵。 此外,我建议使用-loop 并在循环之前重置变量:popMatrix()
forvShapePosY

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();
}

另一种方法是在循环中通过 (0, 100) 逐渐改变平移:

void draw() {

    translate(vShapePosX, vShapePosY);

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

    stop();
}

推荐阅读