2012/05/17

C# game programming - For Serious Game Creation


有用的Timer


using System.Runtime.InteropServices;
namespace GameLoop
{
public class PreciseTimer {
[System.Security.SuppressUnmanagedCodeSecurity] [DllImport("kernel32")]
private static extern bool QueryPerformanceFrequency(ref long
PerformanceFrequency); [System.Security.SuppressUnmanagedCodeSecurity] [DllImport("kernel32")]
private static extern bool QueryPerformanceCounter(ref long PerformanceCount);
long _ticksPerSecond = 0;
long _previousElapsedTime = 0; public PreciseTimer()
{
QueryPerformanceFrequency(ref _ticksPerSecond); GetElapsedTime(); // Get rid of first rubbish result
}
public double GetElapsedTime() {
long time = 0;
QueryPerformanceCounter(ref time);
double elapsedTime = (double)(time - _previousElapsedTime) /
(double)_ticksPerSecond; _previousElapsedTime = time; return elapsedTime;
} }
}
The QueryPerformanceFrequency function retrieves the frequency of the high-resolution performance counter. Most modern hardware has a high- resolution timer; this function is used to get the frequency at which the timer increments. The QueryPerformanceCounter function retrieves the current value of the high-resolution performance counter. These can be used together to time how long the last frame took.
GetElapsedTime should be called once per frame and this will keep track of the time. The elapsed time is so important that it should be incorporated into the game loop. Open the Program.cs file and change the game loop so it takes one argument.
public class FastLoop {
PreciseTimer _timer = new PreciseTimer();
public delegate void LoopCallback(double elapsedTime);
The timer is then called once per frame and elapsed time is passed on to FastLoop’s callback.
void OnApplicationEnterIdle(object sender, EventArgs e) {
while (IsAppStillIdle()) {
_callback(_timer.GetElapsedTime()); }
}
The game loop can now be used to smoothly animate any game! By the end of this chapter, the game loop will be used to smoothly rotate a 3D triangle—the ‘‘Hello World’’ application of OpenGL programming.

No comments:

Post a Comment