Search code examples
javamatrixprocessing

I can not figure out how to make the code build blocks one by one


This is my first time i pose a question here, I am frustrated because I have been trying to figure this out for a few hours now. Why is my code not building each cube separately. Code is supposed to fill the canvas horizontally with cubes, changing line after filling another line.

void setup() {
  size(600,600);
  background(0);
  frameRate(1);
}
int n=0;
int y=0;
int xCoord=0;
void draw() {
    while(n<10)
    {
        for(int i = 0; i<10; i++)
        {
            rect(xCoord, y, 60,60);
            xCoord += 60;
        }
         xCoord = 0; n++; y+=60; 
         
    }
}

Solution

  • Keep in mind that the draw function is called each frame. If you want to animate something, you gotta make sure each frame shows some new information.

    Your while loop completes (and thus builds all the blocks) in one iteration of draw. Thus, you will also see all the blocks drawn after the first iteration of draw completes. Thus, you do not see them built one by one.

    If you want to draw them frame by frame, you need to ensure that you change the amount of blocks between each iteration of draw.

    pseudocode:

    var currentAmountOfBlocks;
    
    fun draw:
       // Draw currentAmountOfBlocks blocks.
       for (i = 0; i <= currentAmountOfBlocks; i++)
       {
           drawBlock();
       }
       currentAmountOfBlocks++
    

    Processing would then call it like this for you, at your desired frameRate

    draw(); // 1 block
    draw(); // 2 blocks
    draw(); // ... blocks 
    draw(); // n blocks
    

    You were basically doing:

    fun draw:
       drawAllBlocks()
    

    Processing calls that like this for you:

    draw(); // all blocks
    draw(); // all blocks
    draw(); // all blocks
    draw(); // all blocks
    

    Yes, you have a while loop counting to ten blocks, but that completes before your first iteration of draw() completes.