c#计算增量时间的麻烦
本文关键字:麻烦 时间 计算 | 更新日期: 2023-09-27 18:06:28
我正在尝试用c#制作一个计时系统,但是我在计算增量时间时遇到了麻烦。
下面是我的代码:private static long lastTime = System.Environment.TickCount;
private static int fps = 1;
private static int frames;
private static float deltaTime = 0.005f;
public static void Update()
{
if(System.Environment.TickCount - lastTime >= 1000)
{
fps = frames;
frames = 0;
lastTime = System.Environment.TickCount;
}
frames++;
deltaTime = System.Environment.TickCount - lastTime;
}
public static int getFPS()
{
return fps;
}
public static float getDeltaTime()
{
return (deltaTime / 1000.0f);
}
FPS计数正常,但是增量时间比它应该的快
System.Environment.TickCount的值在函数执行期间发生变化,这导致deltaTime的移动速度比您预期的要快。
试
private static long lastTime = System.Environment.TickCount;
private static int fps = 1;
private static int frames;
private static float deltaTime = 0.005f;
public static void Update()
{
var currentTick = System.Environment.TickCount;
if(currentTick - lastTime >= 1000)
{
fps = frames;
frames = 0;
lastTime = currentTick ;
}
frames++;
deltaTime = currentTick - lastTime;
}
public static int getFPS()
{
return fps;
}
public static float getDeltaTime()
{
return (deltaTime / 1000.0f);
}