(RESOLVED) How to make a counter which uses button presses?

edited June 2015 in Questions about Code

Hello, i'm very new to processing and just trying to make a counter which will start at 0 and increase in increments of '2' up to a total '255' when i press "W" on my keyboard. (and will continue to count up if the key is held down and stop once released). i also want to be able to have the counter count backwards from its current state when i press "S" on my keyboard also in increments of '2' and go no lower '0'.

so far I've only managed to get the counting up part working but struggling with finding a way to count backwards. any help will be greatly appreciated, I will post my code so far.

int minimumValue = 0;
int interval = 2;
int maximumValue = 255;
int currentValue =0;



void setup() {
  size(200, 200);
}

void draw() {

  background(0);
  if (keyPressed) { 
    if (key == 'W' || key == 'w') {
      int speedUp = currentValue+=interval;
       currentValue = constrain (speedUp, minimumValue, maximumValue);
      text(currentValue, 100, 100);
    }

    if (key == 'S' || key == 's') {
      int speedDown = currentValue+= -interval;
       currentValue = constrain (speedDown, minimumValue, maximumValue);
      text(currentValue, 100, 100);
    }
  }
}


 

Answers

  • If you press Ctrl+t to auto-format your code nicely, you'll notice the problem.

    Your checks for key being S are inside the block of code that executes only when key is W!

    Try moving a curly brace!

  • You might also want to use keyPressed() and keyReleased() instead. And maybe have a "current" variable, which would be the right name for it.

  • thanks for the reply! i didn't know about the auto-format before, it helps a lot :D. I tried moving a curly bracket so the block for "if pressing W" and "if pressing S" are now separate. but having the problem the "S" block of code being unable find speedF, i can see why because it's only initialized in the "W" block of code. is there anyway to pull it out so i can use it for the "S" block?

    i will edit the post to show the new code. thanks again.

  • Rather than comparing both lower & upper cases: if (key == 'W' || key == 'w'),
    replace key for keyCode instead: if (keyCode == 'W') :-bd

  • thanks for the tip! :D

  • edited June 2015 Answer ✓

    You have a lot of variables, and not all of them are useful. Really, you only need six of them: starting_value, current_value, speed_up, speed_down, minimum_value, and maximum_value.

  • you can declare speedf before setup()

  • thank you so much all for the help, i finally managed to get it working at last. will post it above in case someone may find it useful. thanks again! ^_^

Sign In or Register to comment.