【问题标题】:How can I set timer in LIBGDX如何在 LIBGDX 中设置计时器
【发布时间】:2024-01-20 00:05:01
【问题描述】:

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

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 秒后发生变化。但是期间不起作用。问题出在哪里?

【问题讨论】:

    标签: android timer libgdx


    【解决方案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");
    }
    

    【讨论】: