Android 如何在LIBGDX中设置计时器
我想每秒钟(随机)更改气球的位置。我写了这段代码:Android 如何在LIBGDX中设置计时器,android,timer,libgdx,Android,Timer,Libgdx,我想每秒钟(随机)更改气球的位置。我写了这段代码: public void render() { int initialDelay = 1000; // start after 1 seconds int period = 1000; // repeat every 1 seconds Timer timer = new Timer(); TimerTask task = new TimerTask() { public void
public void render() {
int initialDelay = 1000; // start after 1 seconds
int period = 1000; // repeat every 1 seconds
Timer timer = new Timer();
TimerTask task = new TimerTask() {
public void run() {
rand_x = (r.nextInt(1840));
rand_y = (r.nextInt(1000));
balloon.x = rand_x;
balloon.y = rand_y;
System.out.println("deneme");
}
};
timer.schedule(task, initialDelay, period);
Gdx.gl.glClearColor(56, 143, 189, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
camera.update();
batch.setProjectionMatrix(camera.combined);
batch.begin();
batch.draw(balloon, balloon_rec.x, balloon_rec.y);
batch.end();
}
这项工作正在进行中。当我运行程序时,气球的位置在1秒后发生变化。但这段时间不起作用。问题出在哪里?不要在render方法中触发线程,它不安全,可能会导致线程泄漏,许多其他问题,并且维护代码会更困难。要处理时间,请使用一个变量,每次调用render时添加增量时间,当该变量优于1.0f时,表示一秒钟已经过去,您的代码如下所示:
private float timeSeconds = 0f;
private float period = 1f;
public void render() {
//Execute handleEvent each 1 second
timeSeconds +=Gdx.graphics.getRawDeltaTime();
if(timeSeconds > period){
timeSeconds-=period;
handleEvent();
}
Gdx.gl.glClearColor(56, 143, 189, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
camera.update();
batch.setProjectionMatrix(camera.combined);
batch.begin();
batch.draw(balloon, balloon_rec.x, balloon_rec.y);
batch.end();
}
public void handleEvent() {
rand_x = (r.nextInt(1840));
rand_y = (r.nextInt(1000));
balloon.x = rand_x;
balloon.y = rand_y;
System.out.println("deneme");
}