How to keep a color in a fill() the same after mousePressed?

穿精又带淫゛_ 提交于 2019-12-06 15:21:20

Stack Overflow isn't really designed for general "how do I do this" type questions. It's for specific "I tried X, expected Y, but got Z instead" type questions. But I'll try to help in a general sense:

You need to store the state of each cell in a data structure, and then use that data structure to draw your scene.

You could do this with a 2D array, where each cell in the array represents a cell in the grid. You could store the state of the cell, or the color directly.

As Kevin said, you should keep the state of your application in a matrix.

boolean[][] matrix = new boolean[21][21];

When you click on a cell, toggle it

if(!matrix[xpos/scl][ypos/scl]) {
    matrix[xpos/scl][ypos/scl] = true;
} else {
    matrix[xpos/scl][ypos/scl] = false;
}

Inside this loop, check if your current position can be drawn or not

if(matrix[x][y]) {
    fill(204, 102, 0); // an orange color
    rect(xpos, ypos, scl, scl);
}

So your draw() method should look like this

void draw() {
    background(255);
    for (int x = 0; x < cols; x++) {
        for (int y = 0; y < rows; y++) {
            int xpos = x*scl;
            int ypos = y*scl;

            stroke(55);
            if((mouseX >= xpos && mouseX <= xpos+scl) &&
                    (mouseY >= ypos && mouseY <= ypos+scl)){
                fill(75);
                if (mousePressed == true){
                    println("Clicked at: " + xpos + " and " + ypos);
                    if(!matrix[xpos/scl][ypos/scl]) {
                        matrix[xpos/scl][ypos/scl] = true;
                    } else {
                        matrix[xpos/scl][ypos/scl] = false;
                    }
                    fill(100);
                    //here is the desired location for the fill to remain constant even 
                    //after unclicking and leaving hover
                }
                println("Mouse at: " + xpos + " and " + ypos);
            }else{
                fill(50);
            }
            if(matrix[x][y]) {
                fill(204, 102, 0);
                rect(xpos, ypos, scl, scl);
            }
            rect(xpos, ypos, scl, scl);
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!