keypressed() and counter variable correspondence,

Its likely a syntax problem, but I could very well be wrong.

What I'm trying to accomplish with this code is simple. When 'a' is pressed, the counter increase will draw a rectangle identical to the corresponding numbered rectangle on the graph, but with a brighter stroke outline for identification purposes. When 's' is pressed, the counter will decrease and draw a rectangle identical to the corresponding numbered rectangle on the graph. So for example, if I increased the counter from 0-4, pressing 's' will go from 4-3.

The problem I seem to be having is the speed of the counter, as upon execution, it cycles from 0-3 very quickly after a single press of 'a' and from 3-0 on a single press of 's'. I feel like this may come as a result of poor syntax, but nothing I've tried produced the desired result.

    int counter=0;
    void setup(){
      size(800,800);

    }

    void graph(){

     stroke(0);
    line(0,400,800,400); 
       fill(0);

       rect(10,370,10,30);
      rect(30,365,10,35);
      rect(50,400,10,25);
      rect(70,380,10,20);
      rect(90,400,10,30);
      rect(110,375,10,25);
      rect(130,385,10,15);
      rect(150,390,10,10);
      rect(170,400,10,10);
      rect(190,400,10,15);
      rect(210,360,10,40);
      rect(230,400,10,40);
      rect(250,350,10,50);
      rect(270,400,10,45);
      rect(290,340,10,60);
      rect(310,330,10,70);
      rect(330,400,10,55);
      rect(350,335,10,65);
      rect(370,345,10,55);

    }


    void highlight(){

      if (keyPressed)

     {  

    if(key=='a'){
      counter=counter+1;}




    if(key=='s'){
       counter=counter-1;}

                                                 }

        if(counter==0){
          stroke(255);
           rect(10,370,10,30);
        }

         if(counter==1){
           stroke(255);
           rect(30,365,10,35);
                                             }

        if(counter==2){
          stroke(255);

          rect(50,400,10,25);
        }

        if(counter==3){

          stroke(255);

            rect(70,380,10,20);}
     }



    void draw(){

      graph();
      highlight();
                            }

Answers

  • Answer ✓

    Classical problem: use the keyPressed() function instead of the keyPressed state in draw(), because the latter will be true as long as the user presses the key, which usually spawn several frames (there 60 of them per second, by default).

Sign In or Register to comment.