开发者

Compensate drawing delay from the game logic updates

开发者 https://www.devze.com 2023-01-13 11:13 出处:网络
Now I have (1: the UI-loop, there my SurfaceView is placed), (2: a second thread, there the draw function from the UI-loop is called AND the update calculations from my Engine) and (3: the engine, the

Now I have (1: the UI-loop, there my SurfaceView is placed), (2: a second thread, there the draw function from the UI-loop is called AND the update calculations from my Engine) and (3: the engine, there all the calculations stuff are).

Now I wonder how the best and smoothest way to do the SurfaceView independent from the actual frame rate. How shall I do so it will compensate if there is a low frame rate?

I think my current solution isn't enough, see code below.

Thread-class

//Constructor stuff....

int static delay = 0; /* My delay in milliseconds, depends most on
which sort of game I'm trying to make */
@Override
public void run() {
 while (state==RUNNING) {
       long beforeTime = System.nanoTime();
       engine.updateSprites(); //Update calculations from my engine

 //Rita
 Canvas c = null;
 try {     

       c = surfaceHolder.lockCanvas(null);
       synchronized (surfaceHolder) {
           view.myDraw(c);    //My draw function
     }开发者_开发百科
 } finally {
     if (c != null) {
         surfaceHolder.unlockCanvasAndPost(c);
     }
 }

 sleepTime = delay-((System.nanoTime()-beforeTime)/1000000); /* 1000000 because 
 of the nanoTime gives us the current timestamp in nanoseconds */

        try {
            if(sleepTime>0){
            Thread.sleep(sleepTime);          

            }
        } catch (InterruptedException ex) { 
        }

 }

Is this code enough to ensure the independent from low frame rate? If not, where is my way to go?

Thanks in advance!


http://dewitters.koonsolo.com/gameloop.html

This is one of the best short lessons I know. It shows 3 different ways to do what you are looking for.


Now, I'm not experienced enough in this to give you a definitive answer, I'm sure someone will be along soon to give you that. In the meantime however, I will provide my thoughts:

So the question is how to make sure the SurfaceView appears nice and smooth, regardless of the frame rate?

For something like this, I believe a common implementation is to use double/mulitple buffering

Whereby you draw the frame in the background, and as soon as it is ready, you switch the new frame for the old frame.

So imagine you have two canvases A,B.

You display A to the user, while in the background you are preparing B. When the client requests a new frame, you either show them A, or if B is ready, you show them B.

0

精彩评论

暂无评论...
验证码 换一张
取 消