我有一个Android游戏的开始。它具有一个GameLoop(线程)类和GameView(表面视图),该类跟踪fps值,而GameLoop(表面视图)将FpsText对象设置为静态并设置其运行状态,依此类推。
现在,我有一个单独的fpsText.setText(gameloop.getFps());对象,该对象知道如何在屏幕上绘制自身,但要进行更新,我需要执行类似GameView的操作

如果我在FpsText类中执行此操作,这不是问题,但我想尝试使用一个fpsText对象来自行更新。我对线程没有任何其他经验,我认为这可能适得其反,但是我还是尝试将gameloopfpsText引用作为参数传递。毫不奇怪,我每次运行应用程序时都会得到不同的不良结果,所以我想知道您认为处理这种情况的最佳方法是什么?

作为在GameView中更新的替代方法,我总是可以在gameloop类中公开fps值,但是我知道这是不好的做法!听起来都不是好的解决方案,也许有更好的方法?

作为参考,这是我的游戏循环,并实现了RedOrav建议的第二个更改:

package biz.hireholly.engine;

import android.graphics.Canvas;
import android.util.Log;
import android.view.SurfaceHolder;
import biz.hireholly.gameplay.FpsText;

import java.util.ArrayList;


/**
 * The GameLoop is a thread that will ensure updating and drawing is done at set intervals.
 * The thread will sleep when it has updated/rendered quicker than needed to reach the desired fps.
 * The loop is designed to skip drawing if the update/draw cycle is taking to long, up to a MAX_FRAME_SKIPS.
 * The Canvas object is created and managed to some extent in the game loop,
 * this is so that we can prevent multiple objects trying to draw to it simultaneously.
 * Note that the gameloop has a reference to the gameview and vice versa.
 */

public class GameLoop extends Thread {

    private static final String TAG = GameLoop.class.getSimpleName();
    //desired frames per second
    private final static int MAX_FPS = 30;
    //maximum number of drawn frames to be skipped if drawing took too long last cycle
    private final static int MAX_FRAME_SKIPS = 5;
    //ideal time taken to update & draw
    private final static int CYCLE_PERIOD = 1000 / MAX_FPS;

    private SurfaceHolder surfaceHolder;
    //the gameview actually handles inputs and draws to the surface
    private GameView gameview;

    private boolean running;
    private long beginTime = 0; // time when cycle began
    private long timeDifference = 0; // time it took for the cycle to execute
    private int sleepTime = 0; // milliseconds to sleep (<0 if drawing behind schedule)
    private int framesSkipped = 0; // number of render frames skipped

    private double lastFps = 0; //The last FPS tracked, the number displayed onscreen
    private ArrayList<Double> fpsStore = new ArrayList<Double>(); //For the previous fps values
    private long lastTimeFpsCalculated = System.currentTimeMillis(); //used in trackFps
    FpsText fpsText;

    public GameLoop(SurfaceHolder surfaceHolder, GameView gameview, FpsText fpsText) {
        super();
        this.surfaceHolder = surfaceHolder;
        this.gameview = gameview;
        this.fpsText = fpsText;
    }

    public void setRunning(boolean running) {
        this.running = running;
    }
    @Override
    public void run(){

        Canvas c;

        while (running) {
            c = null;
            //try locking canvas, so only we can edit pixels on surface
            try{
                c = this.surfaceHolder.lockCanvas();
                //sync so nothing else can modify while were using it
                synchronized (surfaceHolder){

                    beginTime = System.currentTimeMillis();
                    framesSkipped = 0; //reset frame skips

                    this.gameview.update();
                    this.gameview.draw(c);

                    //calculate how long cycle took
                    timeDifference = System.currentTimeMillis() - beginTime;
                    //good time to trackFps?
                    trackFps();

                    //calculate potential sleep time
                    sleepTime = (int)(CYCLE_PERIOD - timeDifference);

                    //sleep for remaining cycle
                    if (sleepTime >0){
                        try{
                            Thread.sleep(sleepTime); //saves battery! :)
                        } catch (InterruptedException e){}
                    }
                    //if sleepTime negative then we're running behind
                    while (sleepTime < 0 && framesSkipped < MAX_FRAME_SKIPS){
                        //update without rendering to catch up
                        this.gameview.update();
                        //skip as many frame renders as needed to get back into
                        //positive sleepTime and continue as normal
                        sleepTime += CYCLE_PERIOD;
                        framesSkipped++;
                    }

                }

            } finally{
                //finally executes regardless of exception,
                //so surface is not left in an inconsistent state
                if (c != null){
                    surfaceHolder.unlockCanvasAndPost(c);
                }
            }
        }

    }

    /* Calculates the average fps every second */
    private void trackFps(){
        synchronized(fpsStore){
            long currentTime = System.currentTimeMillis();

            if(timeDifference != 0){
                fpsStore.add((double)(1000 / timeDifference));
            }
            //If a second has past since last time average was calculated,
            // it's time to calculate a new average fps to display
            if ((currentTime - 1000) > lastTimeFpsCalculated){


                for (Double fps : fpsStore){
                lastFps += fps;
                }

                lastFps /= fpsStore.size();

                synchronized(fpsText){ //update the Drawable FpsText object
                fpsText.setText(String.valueOf((int)lastFps));
                }

                lastTimeFpsCalculated = System.currentTimeMillis();

                //Log.d("trackFPS()", " fpsStore.size() = "+fpsStore.size()+"\t"+fpsStore.toString());
                fpsStore.clear();


            }
        }
    }

}

最佳答案

您不想要的结果是什么?就获取fps值而言,将fps变量公开并设置getfps()是完全相同的事情,而在GameView中修改fps值将毫无意义。

我怀疑您在GameLoop中所做的事情是在几秒钟之间修改fps变量,即获取GameView也可能读取的中间值。我建议仅每秒修改一次fps,并在两者之间保留时间变量以进行计算。假设您一开始的速度为0 fps。 GameLoop进行计算,一秒钟过去,您已经收集了处理的帧数和时间(1秒)。在此之前,无论GameLoop在做什么,GameView始终都读为0。在那一秒钟之后,假设您完成了60 fps,则修改了fps变量,并且直到下一秒钟都保持不变。因此,在接下来的第二秒,即使GameView对您的变量进行了更多读取,它也将始终获得60。

// Inside GameLoop

private int fps; // Variable you're going to read
private int frameCount; // Keeps track or frames processed
private long lastUpdated;

while(running) {

   if(System.currentTimeMillis() - lastUpdated > 1000) { // 1 second elapsed
      fps = frameCount;
      frameCount = 0;
   }
   frameCount++;
}

public int getFps() {
   return fps;
}


另一种实现方法是将对fpsText的引用传递给GameLoop,GameLoop仅在每秒传递一次之后才对其进行修改。这样,您的渲染线程只需要担心渲染,而GameLoop则需要担心每秒的帧数。但是请记住,您可能会遇到一个竞争条件(在GameLoop中,您的setText()就位于渲染方法的中间),您不必担心其他情况。在渲染和修改时,将fpsText对象包含在同步括号中应该可以解决问题。

让我们知道是否有帮助!

07-27 23:52