2

ゲーム ループを作成するには、この優れたチュートリアルに従いました。しかし、次の FPS の表示に関するチュートリアルは少しわかりにくいと思ったので、1 人で行ってみました。私はtrackFps()自分が作成した方法にかなりの自信を持っています。フレーム間の時間差を計算した後に呼び出され、実行するたびに予測 FPS を測定し、それらの予測 FPS 値を に保存し、ArrayList1 秒が経過すると、予測 FPS を合計し、追加された値の数で割って平均 FPS を取得します。

デバッガーで実行すると正常に機能しますが、通常どおり実行すると、次の例外が発生します。

FATAL EXCEPTION: Thread-11
java.lang.IndexOutOfBoundsException: Invalid index 26, size is 6
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:257)
at java.util.ArrayList.get(ArrayList.java:311)
at biz.hireholly.engine.GameLoop.trackFps(GameLoop.java:120)
at biz.hireholly.engine.GameLoop.run(GameLoop.java:73)

それはかなり説明的で、この行で発生しますfps += fpsStore.get(fpsTrackCount-1);fpsTrackCountしかし、 Variable がどのように 26 まで高くなるかはわかりませんArrayList fpsStore

誰かが私のGameLoopクラス、特にtrackFps()一番下のメソッドを調べますか? まるごとお届けします。多くのコメントがありますが、それほど多くはなく、一部の人にとっては非常によく知られているはずです.

GameLoop(trackFps()下部に FPS の計算方法が含まれています):

package biz.hireholly.engine;

import android.graphics.Canvas;
import android.view.SurfaceHolder;
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 int fpsTrackCount = 1; // number we'll divide the fpsSTore by to get average
    private ArrayList<Double> fpsStore = new ArrayList<Double>(); //For the previous fps values
    private long lastTimeFpsCalculated = System.currentTimeMillis(); //used in trackFps

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

    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(){
        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){
            int fps = 0;
            int toDivideBy = fpsTrackCount;
            while ((fpsStore !=  null) && (fpsTrackCount > 0 )){
                fps += fpsStore.get(fpsTrackCount-1);
                fpsTrackCount--;
            }
            lastFps = fps / toDivideBy;
            lastTimeFpsCalculated = System.currentTimeMillis();
            fpsTrackCount = 1;
            fpsStore.clear();
        }
        else{   
        fpsTrackCount++;
        }
    }
    /* So That it can be drawn in the gameview */
    public String getFps() {
        return String.valueOf(lastFps);
    }

}
4

3 に答える 3

2

わかりました、まずこれを見てみましょう...

java.lang.IndexOutOfBoundsException: Invalid index 26, size is 6
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:257)
at java.util.ArrayList.get(ArrayList.java:311)
at biz.hireholly.engine.GameLoop.trackFps(GameLoop.java:120)

そのため、trackFPS のどこかで get() はばかげて範囲外です...

private void trackFps()
{
    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)
    {
        int fps = 0;
        int toDivideBy = fpsTrackCount;
        while ((fpsStore !=  null || !fpsStore.isEmpty()) && (fpsTrackCount > 0 ) && (fpsTrackCount < fpsStore.getCount()))
        {
            //synchronized(this) {
            fps += fpsStore.get(fpsTrackCount-1);
            fpsStore.remove(fpsTrackCount-1);  //otherwise we'll get stuck because of getCount condition
            fpsTrackCount--;
            //}
        }
        lastFps = fps / toDivideBy;
        lastTimeFpsCalculated = System.currentTimeMillis();
        //fpsTrackCount = 1;
        //fpsStore.clear();
        Log.d("trackFPS()", "fpsTrackCount = "+fpsTrackCount+"\tfpsStore.size() = "+fpsStore.size()+"\t"+fpsStore.toString());
    }
    else   
        fpsTrackCount++;
}

これを試してみてください。うまく機能しない場合は、同期されたブロックのコメントを外してみてください。

TextDrawableに関するあなたの他の問題に関しては、私はあなたのGameViewを見ました...

これがSurfaceChanged()で見つけたものです

  fps = new TextDrawable();
  fps.setText("HELLO");

さて、それを SurfaceCreated() に移動してみませんか? おそらく、多くの surfaceChanged() コールバックを取得していますが、Logcat 呼び出しがないため、それに気づいていませんか? :) TextDrawable が私が見ることができるものからインスタンス化されている唯一の場所です。

于 2012-07-31T11:27:24.170 に答える
-4

このコードはあなたのために働くはずだと思います

cputhrottle=(int) System.currentTimeMillis();
cputhrottle = (int)System.currentTimeMillis() - cputhrottle;cputhrottle=33-cputhrottle;

1 秒あたり 30 フレームなので、役に立ちます。

于 2012-07-31T11:18:08.453 に答える