| 1 |
<xml> |
| 2 |
<head> |
| 3 |
<title>Tips and tricks</title> |
| 4 |
</head> |
| 5 |
<body> |
| 6 |
|
| 7 |
<h3>Calculating frames per second (fps)</h3> |
| 8 |
<p>Author: Sphair</p> |
| 9 |
|
| 10 |
<p>Often you want to know how fast or slow your game is running, and displaying |
| 11 |
a FPS counter can be a handy debug-tool.</p> |
| 12 |
|
| 13 |
<code> |
| 14 |
class Game |
| 15 |
{ |
| 16 |
public: |
| 17 |
void run(); |
| 18 |
void update(); |
| 19 |
void draw(); |
| 20 |
|
| 21 |
int calc_fps(int frame_time); |
| 22 |
|
| 23 |
CL_Font font_fps; |
| 24 |
int fps; |
| 25 |
}; |
| 26 |
|
| 27 |
void Game::run() |
| 28 |
{ |
| 29 |
CL_ResourceManager resources("resources.xml"); |
| 30 |
font_fps = CL_Font("font_gray", &resources); |
| 31 |
|
| 32 |
while(!CL_Keyboard::get_keycode(CL_KEY_ESCAPE)) |
| 33 |
{ |
| 34 |
update(); |
| 35 |
draw(); |
| 36 |
|
| 37 |
CL_Display::flip(); |
| 38 |
CL_System::keep_alive(); |
| 39 |
}; |
| 40 |
} |
| 41 |
|
| 42 |
void Game::update() |
| 43 |
{ |
| 44 |
// Calculate time since last update |
| 45 |
static int start_time = CL_System::get_time(); |
| 46 |
|
| 47 |
int cur_time = CL_System::get_time(); |
| 48 |
int delta_time = cur_time - start_time; |
| 49 |
start_time = cur_time; |
| 50 |
|
| 51 |
fps = calc_fps(delta_time); |
| 52 |
} |
| 53 |
|
| 54 |
int Game::calc_fps(int frame_time) |
| 55 |
{ |
| 56 |
static int fps_result = 0; |
| 57 |
static int fps_counter = 0; |
| 58 |
static int total_time = 0; |
| 59 |
|
| 60 |
total_time += frame_time; |
| 61 |
if(total_time >= 1000) // One second has passed |
| 62 |
{ |
| 63 |
fps_result = fps_counter + 1; |
| 64 |
fps_counter = total_time = 0; |
| 65 |
} |
| 66 |
fps_counter++; // Increase fps |
| 67 |
|
| 68 |
return fps_result; |
| 69 |
} |
| 70 |
|
| 71 |
void Game::draw() |
| 72 |
{ |
| 73 |
CL_Display::clear(); |
| 74 |
|
| 75 |
font_fps.draw(0, 0, "fps: " + CL_String::from_int(fps)); |
| 76 |
} |
| 77 |
</code> |
| 78 |
|
| 79 |
</body> |
| 80 |
</xml> |