Why does this not work? (String)

I asked question earlier on how to access the default textSize, thinking that would help, but it didn't. So here's the problem and some code: I want to write a console and when the text reaches the lowest line, the whole string is moved up a line for each new line of text. So that the new line is always visible. What's interesting, is that if you set a value for textSize the space between each line increases (when using \n). And the space between each line is not constant.

To make it easy to see what happens, I've drawn some lines across the screen.

Here it is with default textSize, and if you run it, you'll se that it's perfect.

String text1 = "OK\n";
int mouseCount = 1;
int scroll;
void setup(){
  size(400,600);
}

void draw(){
  background(102);
  pushMatrix();
  line(0,140,width,140);
  line(0,150,width,150);
  line(0,206,width,206);
  translate(0,scroll);
  text(text1,10,150,60);
  popMatrix();

}

void mouseClicked(){
  if (mouseX>200){
  text1 += "OK\n";
  } else{
    text1 += "OK?\n";
  }
  mouseCount += 1;
  if (mouseCount > 5){
    scroll -= 14;
  }
}

But if I set the textSize to 12 (which is the default textSize) this happens:

String text1 = "OK\n";
int mouseCount = 1;
int scroll;
void setup(){
  size(400,600);
}

void draw(){
  background(102);
  textSize(12);
  pushMatrix();
  line(0,140,width,140);
  line(0,150,width,150);
  line(0,227,width,227);
  translate(0,scroll);
  text(text1,10,150,60);
  popMatrix();

}

void mouseClicked(){
  if (mouseX>200){
  text1 += "OK\n";
  } else{
    text1 += "OK?\n";
  }
  mouseCount += 1;
  if (mouseCount > 5){
    scroll -= 19;
  }
}

Can anyone explain to me what's happening here?

Answers

  • So every 8th line appears one pixel lower than the others.

  • Answer ✓

    Hey,

    i think this occurs because of a rounding-error. You can set the line-height with textLeading().

    String text1 = "OK\n";
    int mouseCount = 1;
    int scroll;
    int lineHeight = 19;
    
    void setup(){
      size(400,600);
      textSize(12);
      textLeading(lineHeight);
    }
    
    void draw(){
      background(102);
      line(0,140,width,140);
      line(0,150,width,150);
      line(0,227,width,227);
      text(text1,10,150+scroll); 
    }
    
    void mouseClicked(){
      if (mouseX>200){
      text1 += "OK\n";
      } else{
        text1 += "OK?\n";
      }
      mouseCount += 1;
      if (mouseCount > 5){
        scroll -= lineHeight;
      }
    }
    

    Hope that helps.

  • Yes, that helped! Thank you :)

Sign In or Register to comment.