How to make timer for a game loop?

前端 未结 5 1758
别跟我提以往
别跟我提以往 2021-02-06 16:21

I want to time fps count, and set it\'s limit to 60 and however i\'ve been looking throught some code via google, I completly don\'t get it.

5条回答
  •  生来不讨喜
    2021-02-06 17:13

    delta time is the final time, minus the original time.

    dt= t-t0
    

    This delta time, though, is simply the amount of time that passes while the velocity is changing.

    The derivative of a function represents an infinitesimal change in the function with respect to one of its variables. The derivative of a function with respect to the variable is defined as

                    f(x + h) - f(x)
    f'(x) = lim    -----------------
            h->0           h
    

    http://mathworld.wolfram.com/Derivative.html

    #include
    #include
    #include
    #include
    #pragma comment(lib,"winmm.lib")
    
    void gotoxy(int x, int y);
    void StepSimulation(float dt);
    
    int main(){
    
      int NewTime = 0;
      int OldTime = 0;
      float dt = 0;
      float TotalTime = 0;
      int FrameCounter = 0;
      int RENDER_FRAME_COUNT = 60;
    
      while(true){
    
            NewTime = timeGetTime();    
            dt = (float) (NewTime - OldTime)/1000; //delta time
            OldTime = NewTime;
    
            if (dt > (0.016f)) dt = (0.016f);  //delta time
            if (dt < 0.001f) dt = 0.001f;
    
            TotalTime += dt;
    
            if(TotalTime > 1.1f){ 
                TotalTime=0;
                StepSimulation(dt);
                }
    
            if(FrameCounter >= RENDER_FRAME_COUNT){           
                // draw stuff
                //Render(); 
    
                gotoxy(1,2);
                printf(" \n");
                printf("OldTime      = %d \n",OldTime);
                printf("NewTime      = %d \n",NewTime);
                printf("dt           = %f  \n",dt);
                printf("TotalTime    = %f  \n",TotalTime);
                printf("FrameCounter = %d fps\n",FrameCounter);
                printf("   \n");
                FrameCounter = 0;
    
            } 
            else{
                gotoxy(22,7);
                printf("%d  ",FrameCounter);
                FrameCounter++;
    
            }
    
    
        }
    
        return 0;
    }
    
    void gotoxy(int x, int y){
        COORD coord;
        coord.X = x; coord.Y = y;
        SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
        return;
    }
    
    void StepSimulation(float dt){
        // calculate stuff
       //vVelocity += Ae * dt;
    
    }
    

提交回复
热议问题