【问题标题】:android: update scores according to the timer's millisecondsandroid:根据计时器的毫秒更新分数
【发布时间】:2014-07-06 06:25:27
【问题描述】:

应用中有一个定时器,编码如下:

private Runnable updateTimerThread = new Runnable() 
{
    public void run() 
    {
        if (game_pause ==false)
        {
            timeInMilliseconds = SystemClock.uptimeMillis() - startTime;
            updatedTime = timeSwapBuff + timeInMilliseconds;

            int secs = (int) (updatedTime / 1000);
            int mins = secs / 60;
            secs = secs % 60;
            int milliseconds = (int) (updatedTime % 1000);
            text_time.setText("" + mins + ":"
                    + String.format("%02d", secs) + ":"
                    + String.format("%03d", milliseconds));
            customHandler.postDelayed(this, 0);     

            if (milliseconds % 10 == 0)
            {
                update_score_level(1);
            }
        }
        else
        {
            text_time.setText("Paused!");
        }
    }
};

问题:

每个if (milliseconds % 10 == 0) 都会更新分数。但是,这样编码虽然时间流畅,但是分数的更新显得极其不流畅(不是线性速度,时快时慢)。

想以这种方式展示: 0:00:100 ---> 得分+1; 0:00:200 ---> 得分+1; 0:00:300 ---> 得分+1; 上面的怎么修改?

谢谢!

【问题讨论】:

    标签: android performance time timer


    【解决方案1】:

    首先,如果您运行上述代码每秒一千次​​trong>,您一定会失败。而且您必须每次都点击milliseconds % 10。 Android 不是 RTOS,所以它会错过很多这些更新。

    相反,计算基于时间的分数(毫秒/10)并将其添加到基本分数中。以下只是伪代码,但它应该让您朝着正确的方向前进:

    long currentScore = 0;
    long lastStartTimeMillis = 0;
    boolean isPaused = true;
    
    void resumeGame() {
        // remember the last time the game was started/resumed
        lastStartTimeMillis = System.currentTimeMillis();
        isPaused = false;
    }
    
    void pauseGame() {
        isPaused = true;
        // ms of last game run
        long runningTime = System.currentTimeMillis() - latStartTimeMillis;
        // add it to the base score
        currentScore += runningTime / 10L;
    }
    
    long getCurrentScore() {
        if( isPaused ) {
            return currentScore;
        } else {
            long runningTime = System.currentTimeMillis() - latStartTimeMillis;
            return currentScore + runningTime / 10L;
        }
    }
    

    当您显示当前分数时,您可以使用getCurrentScore(),如果它正在运行,它会自动添加基于时间的分数。暂停游戏时,您将基于时间的分数添加到基本分数中,因此它可以正确显示。

    使用此代码,您可以大大减少更新显示的次数,并且您不必担心错过关键的 10 毫秒间隔以在正确的时间更新分数。如果您的游戏以 30fps 运行,那么您可以每 30-100 毫秒更新一次——每秒 10 次仍然足够快,用户不会注意到。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-05
      • 2018-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多