if (keyPressed == true)

edited May 2017 in Questions about Code
String name = " " ;

void setup(){
  size(500,500);
  background(0);
}

void draw(){
  fill(255);
  strokeWeight(20);
  text(name,200,200); 
  if (keyPressed == true) {
      delay(220);
      name = name + key;
    }
}

i'd like to stop the name for 10 letters, is it possible ?

Tagged:

Answers

  • Answer ✓

    if(name.length()<10) {

  • omg thank you ^^

  • Using delay is usually a bad idea. You are using it here to slow down the key repeat.

    Look at keyPressed (), the method, instead

  • should i change the frameRate ?

  • edited May 2017
    String name = " " ;
    
    void setup() {
      size(500, 500);
      background(0);
      frameRate(10);
    }
    
    void draw() {
      fill(255);
      textSize(20);
      text(name, 200, 200); 
      if (keyPressed == true) {
        name = name + key;
      }
    }
    

    Better ?

  • edited May 2017 Answer ✓

    No, don't use framerate either

    Instead: use the function keyPressed instead of the variable of the same name

    void keyPressed () {
    
           name=name+key; 
    
    }
    
  • edited May 2017 Answer ✓

    i'd like to stop the name for 10 letters, is it possible ?

    What does this mean? Do you mean that, after 10 key-presses, you wish to stop accepting more keys?

    @Chrisir gave you the solution -- you can combine it with your keypress:

    if (keyPressed == true && name.length()<10) {
      name = name + key;
    }
    

    Or, outside draw():

    void keyPressed () {
      if (name.length()<10) {
        name = name + key;
      }
    }
    
  • omg i am so dumb xD thanks Chrisir it's much better

    Jeremy yes thanks I have already change it on my sketch ;)

  • this

     name = name + key;
    

    is the same as

         name += key;
    

    This (although you don't use it anymore) :

        if (keyPressed == true) {
    

    same as

      if (keyPressed) {
    
  • okay i'll change it later !

  • edited May 2017

    but i did this to erase my name

      void keyPressed() {     
              if (name.length() < 10 && key != CODED && key != BACKSPACE) {
                name += key;
              } else if (key == BACKSPACE && name.length() > 0) {
                name = name.substring (0, max(0, name.length()-1));
              }
      }
    
  • well done!

  • edited May 2017

    keyPressed must be with small letter at beginning (otherwise it's not called automatically)

Sign In or Register to comment.