实现多线程的正确方式,同时使用游戏循环。

huangapple go评论69阅读模式
英文:

What is the proper way to implement multi threading while using a gameLoop

问题

我正在开发一个游戏,通过键盘输入来移动汽车图像。目前我正在使用以下游戏循环:

private void runGameLoop() {
    window.setVisible();
    isRunning = true;
    final double FRAMES_PER_SECOND = 60;
    double timePerUpdate = 1000000000 / FRAMES_PER_SECOND;
    double timeFromLastUpdate = 0;
    long now;
    long last = System.nanoTime();
    while (isRunning) {
        now = System.nanoTime();
        timeFromLastUpdate += (now - last) / timePerUpdate;
        last = now;
        if (timeFromLastUpdate >= 1) {
            tick();
            render();
            timeFromLastUpdate--;
        }
    }
}

tick 方法更新汽车图像位置,render 方法将图像(带有新位置)渲染到屏幕上。
我希望将计算新图像位置的过程放在单独的线程中,因为目前这些计算太耗时,导致渲染出现延迟。在实现游戏循环的同时是否有办法使用多线程?提前感谢。

英文:

I'm working on a game where I move a car image based on keyboard input. Currently I'm using this game loop:

private void runGameLoop() {
        window.setVisible();
        isRunning = true;
        final double FRAMES_PER_SECOND = 60;
        double timePerUpdate = 1000000000 / FRAMES_PER_SECOND;
        double timeFromLastUpdate = 0;
        long now;
        long last = System.nanoTime();
        while (isRunning) {
            now = System.nanoTime();
            timeFromLastUpdate += (now - last) / timePerUpdate;
            last = now;
            if(timeFromLastUpdate >= 1) {
                tick();
                render();
                timeFromLastUpdate--;
            }
        }
    }

The tick method updates the car image location, and the render method will render the image(with the new location) on screen.
I want to have the calculations for the new image location on a separate thread, because at the moment the calculations are taking to long and causing a rendering lag. Is there a way to use multi threading while still implementing a game loop?
Thanks in advance.

答案1

得分: 1

也许你可以尝试类似于 Android 的做法。在 Android 中,有一个主线程,类似于你的游戏循环。它有一个处理器(Handler)用于在后台/并发线程中向主线程发布的可运行任务。

因此,在每个循环周期中,主线程会执行从后台线程发布的任何可运行任务。

需要注意的是,计算不应该在可运行任务中完成(这些任务在主线程中执行),只应该在可运行任务中传递结果/更新内容。

英文:

Perhpas you can do something similar to what Android does. In Android there is the mainthread which would be like your game loop. It has a Handler for runnables that are posted from background/concurrent threads to the mainthread.

So at every loop cycle the mainthread executes any runnables posted feom background threads.

Note, that the calculations should not be done in the runnables (which are executed in mainthread), only passing the results/updating stuff should be done in the runnables.

huangapple
  • 本文由 发表于 2020年10月4日 19:54:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/64194280.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定