How to add java typing text

2019-09-08 09:08发布

问题:

I'm trying to add some text effects to my game by making the text "type" Here, maybe the pseudocode will make it understandable.

String text = "But what I do have are a very particular set of skills, skills I have acquired over a very long career.";

char = characters(text) ///turn string into list/array of letters

i = 0; //initializes i

while (i < text.length) {
    print(char.letter[i]) ///print 'i'th letter in list (starting with 1)

    TimeUnit.MILLISECONDS.sleep(100) //wait 1/10th of second

    i++; //repeat for all letters
}

P.S. comments with triple slashes are things i don't know how to do

回答1:

Simply use for-each loop over chars of input text:

String text = "...";
for(char c : text.toCharArray()) { 
    System.out.print(c); 
    Thread.sleep(100);  
}
System.out.println();


回答2:

While Sasha's answer already outlines how to do it, to create a really nice-looking typing effect it's important to not always wait the same time between keystrokes.

A human types at different speeds. Usually they have longer pauses before special letters that lie in inconvenient places on the keyboard (think 'z','`' and similar) and makes a longer pause before beginning a new word (or new sentence)

As such you should for the best "typing" experience add a randomization to the sleep-time you have in your game.
Consider the following:

String text = "...";
for (char c : text.toCharArray()) {
    // additional sleeping for special characters
    if (specialChars.contains(c)) {
       Thread.sleep(random.nextInt(40) + 15);
    }
    System.out.print(c);
    Thread.sleep(random.nextInt(90) + 30);
}

These numbers could probably use a little fine-tuning, but that should give you the gist of what's necessary