原文:http://lazyfoo.net/tutorials/SDL/22_timing/index.php
Timing
计时
Last Updated 3/10/14
Another important part of any sort of gaming API is the ability to handle time. In this tutorial we‘ll make a timer we can restart.
对于任何游戏API,另一个重要的部分是能够处理时间参量。在这个教程中,我们将写一个能够重启的定时器。
//Using SDL, SDL_image, SDL_ttf, standard IO, strings, and string streams #include <SDL.h> #include <SDL_image.h> #include <SDL_ttf.h> #include <stdio.h> #include <string> #include <sstream>
For this tutorial we‘ll be using string streams and have to include the sstream header which should come standard with your C++ compiler.
在这个教程中,将使用到string streams,并且include了stream头文件,你的c++编译器应该有这个头文件。
bool loadMedia() { //Loading success flag bool success = true; //Open the font gFont = TTF_OpenFont( "22_timing/lazy.ttf", 28 ); if( gFont == NULL ) { printf( "Failed to load lazy font! SDL_ttf Error: %s\n", TTF_GetError() ); success = false; } else { //Set text color as black SDL_Color textColor = { 0, 0, 0, 255 }; //Load prompt texture if( !gPromptTextTexture.loadFromRenderedText( "Press Enter to Reset Start Time.", textColor ) ) { printf( "Unable to render prompt texture!\n" ); success = false; } } return success; }
As mentioned in the, you want to minimize the amount of times you render text. We‘ll have a texture to prompt input and a texture to display the current time in milliseconds. The time texture changes every frame so we have to render that every frame, but the prompt texture doesn‘t change so we can render it once in the file loading function.
正如font rendering tutorial中所提到的,减少文字渲染所需的时间。我们用一个texture来展示输入信息和一个texture来显示时间(ms)。time texture在每一帧中都变化,所以不得不渲染每一帧。但是prompt texture 并不变,所以只用在加载文件的函数中渲染一次就可以。