How to change text with keyPressed function?

edited January 2017 in Questions about Code

Hello everyone. Here is my problem. I want to change 4 different texts with 3 different keys.

I would like to achive this: When I run the program it appears text nr.1 ("text before the game").

And then when I press the "t" key, appears text nr.2 ("0:0:0") and the previous text (text nr.1) dissapears.

And then when I press the "h" key, appears text nr.3 ("halftime") and the previous text (text nr.2) dissapears.

And the last step, when I pressed the "f" key, appears text nr.4 ("fulltime") and the previous text (text nr.3) dissapears.

I want to display only one text on the sketch at the time.

So far I achived this:

boolean beforeGame = true;
boolean timer = false;
boolean halfTime = false;
boolean fullTime = false;

void setup() {
  size(640, 360);
}

void draw() {
  background(0);

  fill(255);
  textAlign(CENTER);
  textSize(15); 
  
  if (beforeGame)
    text("Text before game ", width / 2, height /2);
  else if(timer)
    text("00 : 00 : 00", width / 2, height / 2);
  else if(halfTime)
    text("HALFTIME", width / 2, height / 2);
  else if(fullTime)
    text("FULLTIME", width / 2, height / 2);
}

void keyPressed() {
  
  if (key == 't')
    timer = true;
    beforeGame = false;
    
  if (key == 'h')
    halfTime = true;
    //beforeGame = false;
    //timer = false;
    //fullTime = false;
    
  if (key == 'f')
    fullTime = true;
    //beforeGame = false;
    //timer = false;
    //beforeGame = false;
    //halfTime = false;
}

Answers

  • Answer ✓

    You are not using brackets properly in your keyPressed function. Here is an alternative way to write your code or throw some brackets in those if statements:

    void keyPressed() {
    
      beforeGame = timer = beforeGame = halfTime = false;
    
      if (key == 't')
        timer = true;  
    
      if (key == 'h')
        halfTime = true;
    
      if (key == 'f')
        fullTime = true;  
    }
    

    Kf

  • Hahaha so simple solution. Thank you.

Sign In or Register to comment.