Thursday 10 September 2015

Decoupling the Physics

Proof of concept (see http://digital-minds-blog.blogspot.com/2014/12/fixed-delta.html)

The point is to keep the gameplay speed consistent regardless of how fast the users PC can render the graphics. So, as a test, the game should run at the same speed with monitor VSYNC turned on and off. VSYNC turned on kind of emulates a PC with lower rendering rates.

Not only would it mess the game up on different PC's, but it would make online play impossible!

You can see the problem when the loop depends on the frame rate:




Here it is decoupled:



A nod to Glenn Fiedler for a great article on the topic:

http://gafferongames.com/game-physics/fix-your-timestep/

Here's the game loop:

1:    //  
2:    // calculate timing metrics  
3:    //  
4:    double new_time = SDL_GetTicks();  
5:    double frame_time = (new_time - current_time) /1000;  
6:    
7:    if ( frame_time > target_frame_time)  
8:      frame_time = target_frame_time;  
9:    
10:    current_time = new_time;  
11:    accumulator += frame_time;  
12:    
13:    //  
14:    // update physics as many times as possible in remaining frame time  
15:    //  
16:    while ( accumulator >= physics_step ){  
17:      getDefaultCamera()->update( physics_step );  
18:      for( unsigned int i = 0; i < physics_list.size(); ++i ) {  
19:    
20:        physics_list[i]->update( physics_step );  
21:      }  
22:      accumulator -= physics_step;  
23:    }  
24:    
25:    //  
26:    // do rendering  
27:    //  
28:    translate( getDefaultCamera()->getViewport().x, getDefaultCamera()->getViewport().y );
29:    render();  

1 comment: