android - 如何在 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 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();

}

initialDelay 正在工作。当我运行程序时,气球的位置在 1 秒后发生变化。但是期间不工作。问题出在哪里?

最佳答案

不要在 render 方法中触发线程,它不安全,会导致线程泄漏,还有很多其他问题,并且会更难维护您的代码,要处理时间,请使用每次调用 render 时添加增量时间的变量,当这个变量是 superior a 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");
}

关于android - 如何在 LIBGDX 中设置定时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37163083/

相关文章:

android - 如果我将我的应用分发到其他应用商店,Google 的应用内购买是否仍然有效

java - osmdroid 中缺少图 block

Android 架构组件 : using ViewModel for RecyclerView items

java - 使用 Android Gallery 作为自动幻灯片放映

timer - Swift:测试 NSTimer 的过期/失效似乎失败

java - 自动移动 Sprite libGDX

java - LIBGDX - 标签与字体大小不匹配

java - Android布局-设置相对于屏幕尺寸的圆角半径

azure - 计时器触发的Azure函数不规则执行

java - 错误 :Gradle: Execution failed for task ':core:compileJava' . LIBGDX