libGDX 标签有时会在每毫秒更新时停止
libGDX label sometimes stops when updating every millisecond
我正在尝试在 libGDX 中每毫秒更新一个标签,持续一段时间。
但是,有时标签突然停止而没有错误,或者我收到 "String index out of range" 错误,然后我的程序崩溃了。这是两个不同的问题。
代码:
Stage stage;
Timer timer = new Timer();
Label countUpLabel;
int countUp;
@Override
public void create () {
stage = new Stage(new FitViewport(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()));
//Setting up time label
BitmapFont font = new BitmapFont(Gdx.files.internal("04b_19__-32.fnt"));
LabelStyle labelStyle = new LabelStyle(font, Color.WHITE);
countUpLabel = new Label("Time:\n00000", labelStyle);
countUpLabel.setPosition(200,200);
countUpLabel.setAlignment(Align.center);
countUpLabel.setFontScale(3);
stage.addActor(countUpLabel);
//Setting up timer
timer.schedule(new TimerTask() {
@Override
public void run() {
if (countUp < 3000) {
countUp++;
countUpLabel.setText(String.format("Time:\n%d", countUp));
}else
timer.cancel();
}
}, 0, 1); //every millisecond run the timer
}
提前致谢。
大多数 libGDX 都不是线程安全的,除非明确声明它是。此外,每毫秒更新一次标签,虽然它仅大约每 16 毫秒(典型显示设备的刷新率)显示一次,但并不是一个很好的方法。所以你可能想删除你的 timer
并在它实际可见时更新标签:在渲染方法中:
float counter = 0f;
@Override
public void render() {
if (counter < 3) {
counter += Gdx.graphics.getDeltaTime();
countUpLabel.setText(String.format("Time:\n%01.22f", counter));
}
// call glClear, stage.act, stage.draw, etc.
}
我正在尝试在 libGDX 中每毫秒更新一个标签,持续一段时间。
但是,有时标签突然停止而没有错误,或者我收到 "String index out of range" 错误,然后我的程序崩溃了。这是两个不同的问题。
代码:
Stage stage;
Timer timer = new Timer();
Label countUpLabel;
int countUp;
@Override
public void create () {
stage = new Stage(new FitViewport(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()));
//Setting up time label
BitmapFont font = new BitmapFont(Gdx.files.internal("04b_19__-32.fnt"));
LabelStyle labelStyle = new LabelStyle(font, Color.WHITE);
countUpLabel = new Label("Time:\n00000", labelStyle);
countUpLabel.setPosition(200,200);
countUpLabel.setAlignment(Align.center);
countUpLabel.setFontScale(3);
stage.addActor(countUpLabel);
//Setting up timer
timer.schedule(new TimerTask() {
@Override
public void run() {
if (countUp < 3000) {
countUp++;
countUpLabel.setText(String.format("Time:\n%d", countUp));
}else
timer.cancel();
}
}, 0, 1); //every millisecond run the timer
}
提前致谢。
大多数 libGDX 都不是线程安全的,除非明确声明它是。此外,每毫秒更新一次标签,虽然它仅大约每 16 毫秒(典型显示设备的刷新率)显示一次,但并不是一个很好的方法。所以你可能想删除你的 timer
并在它实际可见时更新标签:在渲染方法中:
float counter = 0f;
@Override
public void render() {
if (counter < 3) {
counter += Gdx.graphics.getDeltaTime();
countUpLabel.setText(String.format("Time:\n%01.22f", counter));
}
// call glClear, stage.act, stage.draw, etc.
}