2013-01-31 99 views
-1

大家好我試圖限制我的FPS到30與下面的代碼,但我不知道它的工作。限制幀每秒

while (runthread){ 

      c = null; 
      timestart = System.currentTimeMillis();       //Get time at start of loop for FPS calc 

      try{ 
      c=mySurfaceHolder.lockCanvas();         //Set c (Canvas) to locked 

      synchronized(mySurfaceHolder){ 
      framesskipped = 0;            // resetting frames skipped (as this is about to render to the screen, the frames skipped variable is only incremented when the onDraw() method is skipped, once it's run, reset it back to 0 for the next count 
      doDraw(c);              //Draw game world 
      updateMenu(); //Update game logic 

      } 
      } 
      finally{ 
       if (c != null){ 

       mySurfaceHolder.unlockCanvasAndPost(c);      //Unlock and post 

       } 
      } 

      //work out timings 

       timeend = System.currentTimeMillis();      //get end time for current frame (for FPS) 
       frametime = timeend-timestart;        //Set the frametime variable to the time the frame took to render & update (end time - start time) 
       sleepfor = (int) (30.3030303030303-frametime);    // this is the time that the thread will sleep for if <target time (1000/33 = apx. 30FPS 


       if (sleepfor>0){           // If the 'sleepfor' variable is >0 then set the thread to sleep for it's value (expressed in milliseconds) 

        try { 
         MainThread.sleep(sleepfor);       //send thread to sleep for value of sleepfor (determined above). 

        } catch (InterruptedException e) {}      //in case of exception 
       }               //close if statement 


        while (sleepfor<0 && framesskipped<maxframesskipped){ //if sleepfor is < 0 (ie, frame took longer to render than target time and the maxframesskipped has not reached it's limit) 
         updateMenu();          //Update game logic only 
         sleepfor+=33;          //time to sleep plus the time frame took to render 
         framesskipped++;         //add one to framesskipped variable so this only skips a certain number of frames 
         frame=0; 
         } 

從我的日誌中輸出我放在我的onDraw方法。

enter image description here

正如你所看到的,它看起來並不進行限制,以30fps的,我不知道爲什麼,我的人物一定是錯誤的。其次,任何人有任何想法,爲什麼我的幀數下降到5時不時??

謝謝

+0

太棒了!投票決定沒有任何理由,爲什麼投票反對 - 我對這些非常興奮,他們非常有幫助 - 謝謝! – Zippy

回答

0

我發現了問題所在:

sleepfor = (int) (30.3030303030303-frametime); 

本來應該

sleepfor = (int) ((1000/fps)-frametime); 

所以 sleepfor =(INT)(33.3333333-幀時間);

改變它,它在30/31 fps運行相當不錯