简体   繁体   中英

How to draw text, char by char in LWJGL/Slick2D

I want ask that someone know how to draw string, char by char in the interval, for example, 0.25sec?

"H" (0.25sec) "e" (0.25sec) "l" (0.25sec) "l" (0.25sec) "o";

I use drawText(x, y, String); to draw text.

To do this nicely in slick, I recommend utilizing the update() method in your game. For each update tick, you can have a variable count how many milliseconds (approximate) have passed with the delta (how long it took to update), and then tack on a letter after your determined time amount (the speed at which you want it to add letters).

If you want this to be something you will be using throughout your game, I definitely recommend making it into it's own class, such as a messageFeed or messageWriter or whatever you'd like it to be called.

Here is a quick example I wrote:

public class TextFieldTest extends BasicGameState{

    private int stateId = 0;
    String text = "This is a line of text blah blah blah";
    String currentText = "";
    int count = 0;
    int index = 0;

    public TextFieldTest(int State) {
        this.stateId = State;
    }

    public void init(GameContainer gc, StateBasedGame sbg) throws SlickException{

    }

    public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException{
        g.drawString(currentText, 40, 40);
    }

    public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException{
        if(count < 25) {
            count+=delta;
        } else {
            count = 0;
            if(index < text.length()) {
                currentText += text.charAt(index++);
            }
        }
    }

    public int getID(){
        return this.stateId;
    }
}

In this example I use 25 as my threshold, and once I break that threshold I add a new letter to be shown, then start my count back over again. MUCH easier than using System time stuff, as slick already gets the delta for you. You can mess around with this example to get it exactly how you want, and you can even have a variable in place of the 25 so you can change the text speed you'd want it at.

You can measure elapsed time with System.nanoTime().

See: http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#nanoTime()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM