Android FPS,如何让它更流畅?

时间:2011-12-27 12:42:42

标签: android loops frame-rate smooth

我在构建游戏的基本游戏循环时遇到了麻烦。我处于早期阶段,我想要做的就是以恒定的速度(例如3)将球移动到屏幕的底部。球的位置在主面板更新方法中更新,并按预期在渲染部分中绘制。这个机制没什么特别的。球移动但它肯定不平滑,视觉安静令人不安。我测量了这些方法的实施时间,这对夫妇的总实施时间约为3-4毫秒。在这种情况下,什么是合适的FPS?给定的常量值是否适合我的机制中缺少什么或错误?非常感谢提前。主线程中的代码块。

private final static int MAX_FPS = 200;
private final static int FRAME_PERIOD = 1000 / MAX_FPS;
private final static int    MAX_FRAME_SKIPS = 5;

public void run() {

    initTimingElements();
    long beginTime;
    long timeDiff;
    int sleepTime;
    int framesSkipped;
    long beginTime2;

    long diff1;
    long diff2;

    sleepTime = 0;

    Canvas canvas;
    Log.d(TAG, "Starting game loop");
    while (running) {
        canvas = null;
        try {
            canvas = this.surfaceHolder.lockCanvas();
            synchronized (surfaceHolder) {
                beginTime = System.currentTimeMillis();
                framesSkipped = 0; 

                this.gamePanel.update();
                diff1=System.currentTimeMillis()-beginTime;
                beginTime2=System.currentTimeMillis();
                this.gamePanel.render(canvas);
                diff2=System.currentTimeMillis()-beginTime2;



                timeDiff = System.currentTimeMillis() - beginTime;
                sleepTime = (int) (FRAME_PERIOD - timeDiff);

                if (sleepTime > 0) {
                    try {
                        Thread.sleep(sleepTime);
                    } catch (InterruptedException e) {
                    }
                }                   
                while (sleepTime < 0 && framesSkipped < MAX_FRAME_SKIPS) {
                    this.gamePanel.update();
                    sleepTime += FRAME_PERIOD;
                    framesSkipped++;
                }
                if (framesSkipped > 0) {
                    Log.d(TAG, "Skipped:" + framesSkipped);
                }
                framesSkippedPerStatCycle += framesSkipped;
                storeStats();
            }
        } finally {
            if (canvas != null) {
                surfaceHolder.unlockCanvasAndPost(canvas);
            }
        }
    }
}

1 个答案:

答案 0 :(得分:-1)

尝试使用每隔60ms左右触发一次的TimerTask 这就是我做的事情,直到我不再懒得去做一个正确的实现,但它运作良好。 请记住run()将在不同的线程中执行,因此使用runOnUIThread()来运行您需要的任何代码。