Constrain() and using arrow keys

edited May 2016 in Using Processing

Im trying to make a system where the following occurs;

a float constrained between -2 and 2 is used to define certain states

i.e -2 will print W, -1 will print SW, 0 will print E, 1 will print SE and two will print E

using conditionals, the program will print according to which state its at (for example , no key = 0, if left key is hit, state becomes -1, if hit again its -2 and cannot go past. if you want a positive you must hit the opposite key (from -2 to 2, the right arrow key must be hit 4 times) and vice versa from 2 to -2.

float state = 0;

void setup(){

void draw(){

void numberControl(){
  if (keyPressed ==true && key == CODED && keyCode == LEFT){
    constrain(state + 1,-2,2);
    if (constrain(state + 1,-2,2) == -1){
      text(""+ constrain(state + 1,-2,2), width/2,height/2);

I have gotten to the 1st part and It goes past the boundary set and loops. I know draw continually loops but I cannot think how to achive what im trying to do without calling the numberControl method in draw. Any Suggestions?


  • constrain(state + 1,-2,2);

    you aren't assigning the result to anything here...

  • I thought constrain would then be limited. Do I need another variable to store the constrained variable?

  • The java doc didn't explain well

  • Answer ✓

    The function constrain() does not make any changes to any variables. If you wish to limit a variable to a certain range of values, you should use constrain in conjunction with an assignment statement:

    float number = 12;
    number = constrain(number, 0, 10); // number is now 10
    constrain(number, 1, 3); // returns 3, but this value is not saved anywhere; number is still 10
  • The function constrain() does not make any changes to any variables.

    Moreover, even if it wanted to, it simply can't! Java doesn't allow that! :P

  • ok, well is there a way to ensure that a variable doesn't go beyond set limits?

  • Answer ✓

    just assign the value back to the variable you're checking

    number = constrain(number, 0, 10);

    or -2, 2 in your case.

Sign In or Register to comment.