我是 Java 新手,我正在尝试制作一款视觉小说类型的游戏。 我想做的是通过按空格按钮逐行显示文本文件中的文本,就像在通常的小说中一样。 我忽略了不同的方法,但对我来说没有任何效果。我知道有 Scanner 和 BufferedReader,但是它们适合我正在做的事情吗? 现在发生的事情是,当我按“空格”时,整个文本都会出现在屏幕上,当我松开时,它就会消失。
这是我的游戏类:
public class NovelGame extends Game {
public static final int WIDTH = 1366;
public static final int HEIGHT = 768;
public SpriteBatch batch;
public String txtFileString;
public String lines[];
public BitmapFont bitmapFont;
@Override
public void create () {
batch = new SpriteBatch();
bitmapFont = new BitmapFont();
this.setScreen(new MainMenuScreen(this));
txtFileString = Gdx.files.internal("script.txt").readString();
String[] anArray = txtFileString.split("\\r?\\n");}
@Override
public void render () {
super.render();
}}
这是我的游戏屏幕类:
public class MainGameScreen implements Screen{
private Texture img;
NovelGame game;
public MainGameScreen (NovelGame game) {
this.game = game;
}
@Override
public void show() {
img = new Texture("bck.jpg");
}
@Override
public void render(float delta) {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); // This cryptic line clears the screen.
game.batch.begin();
game.batch.draw(img, 0, 0);
if(Gdx.input.isKeyPressed(Input.Keys.SPACE)){
game.bitmapFont.draw(game.batch, game.txtFileString,Gdx.graphics.getWidth()/2,Gdx.graphics.getHeight()/2);
}
game.batch.end();
}
我有一个想法使用 while 和 if 来显示它,但无法确切地弄清楚如何做到这一点。
编辑:我找到了一种显示文本的方法,但是现在,一旦我运行我的游戏,在我按下空格键后,它就会开始无休止地堆叠一个文本。
代码:
public class MainGameScreen implements Screen{
private Texture img;
NovelGame game;
public MainGameScreen (NovelGame game) {
this.game = game;
}
@Override
public void show() {
img = new Texture("bck.jpg");
}
@Override
public void render(float delta) {
try {
BufferedReader br = new BufferedReader (new FileReader("C:\\Users\\hydra\\Documents\\JAVA_PROJECTS\\gamespace\\core\\assets\\startd.txt"));
while((game.strLine = br.readLine()) != null){
game.list.add(game.strLine);
}
br.close();
} catch (IOException e) {
System.err.println("Unable to read the file.");
}
if(Gdx.input.isKeyJustPressed(Input.Keys.SPACE)){
game.showText = true;
}
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); // This cryptic line clears the screen.
game.batch.begin();
game.batch.draw(img, 0, 0);
if(game.showText) {
for(int i = 0; i < game.list.size(); i++) {
System.out.println(game.list.get(i));
game.bitmapFont.draw(game.batch, game.list.get(i), 100, 50);
}
}
game.batch.end();
}
最佳答案
问题就出在这里。如果当前只有一个键按下,Gdx.input.isKeyPressed
返回true
。
if(Gdx.input.isKeyPressed(Input.Keys.SPACE)){
game.bitmapFont.draw(game.batch, game.txtFileString,Gdx.graphics.getWidth()/2,Gdx.graphics.getHeight()/2);
}
要解决此问题,请添加一个 boolean 标志,仅在按下按键后激活它:
if(Gdx.input.isKeyJustPressed(Input.Keys.SPACE)){
showText = true;
}
在渲染方法中:
if (showText) {
game.bitmapFont.draw(game.batch, game.txtFileString,Gdx.graphics.getWidth()/2,Gdx.graphics.getHeight()/2);
}
关于java - libGDX:如何在按键后逐行读取和显示 .txt 文件中的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52245438/