如何在LIBGDX中设置计时器 [英] How can I set timer in LIBGDX

查看:86
本文介绍了如何在LIBGDX中设置计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想每秒钟(随机)更改气球的位置.我写了这段代码:

I want to change my balloon's location (randomly) in every second. I wrote this code:

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秒钟后,气球的位置正在改变.但是期间不起作用.问题出在哪里?

initialDelay is working. Balloon's location is changing after 1 second when I run program. But period is not working. Where is the problem?

推荐答案

请勿在render方法内触发线程,因为这样做不安全,会导致线程泄漏,其他许多问题,并且会更难以维护您的代码,为了处理时间,请使用一个变量,该变量会在每次调用render时添加增量时间,当此变量大于1.0f时,表示一秒钟过去了,您的代码将如下所示:

Don't fire threads inside the render method, it's not safe, can cause thread leaks, a lot of other problems and will be harder to maintain your code, to handle time use a variable adding delta time every time render is called, when this variable is superior a 1.0f means that one second has passed, your code would be something like this:

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");
}

这篇关于如何在LIBGDX中设置计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆