Drawing just one shape on keyPressed

Hey everybody! I know that this probably has a very simple answer, but I can't seem to figure it out by myself.

So I want to draw a shape whenever a key is pressed. So far so good. I also want them to appear randomly on the screen, and I managed to do that also. The problem is that when I press the key, it draws a few shapes instead of just one.

This is the code:

void setup(){
 size(400, 400); 
 background(255);
}

void draw(){
 if (keyPressed){
  if (key == 'b' || key == 'B'){ 
   fill(random(255), random(255), random(255), random(255));
   noStroke();
   rect(random(400), random(400), 40, 40, 20, 0, 20, 0); 
  }
  if (key == 'c' || key == 'C'){
    fill(random(255), random(255), random(255), random(255));
    noStroke();
    rect(random(400), random(400), 50, 50, 25, 25, 0, 0);
  }
 }
}

Thank you so much for your help in advance!

Answers

  • Instead of checking the keyPressed boolean variable in your draw() loop. Utilize the keyPressed(){} event function. It will fire once when a key is pressed.

    void setup(){
     size(400, 400); 
     background(255);
    }
    
    void draw(){
    }
    
    void keyPressed(){
    
      if (key == 'b' || key == 'B'){ 
       fill(random(255), random(255), random(255), random(255));
       noStroke();
       rect(random(400), random(400), 40, 40, 20, 0, 20, 0); 
      }
      if (key == 'c' || key == 'C'){
        fill(random(255), random(255), random(255), random(255));
        noStroke();
        rect(random(400), random(400), 50, 50, 25, 25, 0, 0);
      }
    
    }
    
Sign In or Register to comment.