java - 这是一个合适的 Android 游戏循环吗?

标签 java android

我从我正在学习的书中抓取了这个。

public void run()
{
    // this is the method that gets called when the thread is started.

    // first we get the current time before the loop starts
    long startTime = System.currentTimeMillis();

    // start the animation loop
    while (running)
    {
        // we have to make sure that the surface has been created
        // if not we wait until it gets created
        if (!holder.getSurface ().isValid())
            continue;

        // get the time elapsed since the loop was started
        // this is important to achieve frame rate-independent movement,
        // otherwise on faster processors the animation will go too fast
        float timeElapsed = (System.currentTimeMillis () - startTime);

        // is it time to display the next frame?
        if (timeElapsed > FRAME_RATE)
        {
            // compute the next step in the animation
            update();

            // display the new frame
            display();

            // reset the start time
            startTime = System.currentTimeMillis();
        }
    }

    // run is over: thread dies
}

它是否正确地考虑了延迟并且是最优的?

我的意思是,如果视频不能每秒更新 60 次,update() 是否会被调用每秒 60 次?

谢谢

最佳答案

if the video cannot update 60 times per second will the update() be called 60x per second?

答案是否定的。在每个游戏循环开始时,您计算自上次游戏循环以来已经过了多长时间。您将其存储在“timeElapsed”中。

从这里,您将其与“FRAME_RATE”进行比较。 “FRAME_RATE”是一个误导性的名称,因为在您的情况下,这不是您的帧速率。您需要 60 的帧速率。为了等待适当的时间量,FRAME_RATE 应为 1000(毫秒)/60(每秒帧数)。

现在,在每次迭代开始时,您会计算耗时并测试是否到了下一帧的时间。如果不是,则跳过任何实际处理或渲染,然后再次运行循环。

当耗时最终超过 FRAME_RATE(这实际上是帧延迟)时,您将执行处理并渲染帧。理想情况下,执行此操作所需的时间将少于您的帧延迟,从而使您的下一次迭代能够按计划开始。只要是这种情况,update() 和 display() 就会每秒被调用大约 60 次。

但是,如果渲染和处理帧所花费的时间比帧延迟长,那么下一帧将在下一次迭代中处理,并且它将是晚了。在这种情况下,每秒调用 update() 和 display() 的次数将少于 60 次。

关于java - 这是一个合适的 Android 游戏循环吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12851381/

相关文章:

java - 使用 Google KMS 和 Entrust 证书签署 PDF 文档

java - 共享首选项不会保存数据

java - 使用内部联接查询运行 count() 时,Room 返回包含一项的列表,而不是空列表

java - ESRI 框架 : java vs javascript

java - 为什么我同时在 HashMap 上迭代和修改时没有得到 "ConcurrentModificationException"?

java - 更改了DB,更新了DB版本无法添加数据也无法不添加数据

java - 用java Ping到多平台

java - 从 URL 获取 JSON,选择值并将其存储到 textView 中

android - 在复制期间在 couch base lite 的 android 模拟器中获取 http 404 错误

java - 如何按字母顺序设置 ListView?