【问题标题】:C# Trouble Calculating Delta TimeC# 计算增量时间的问题
【发布时间】:2015-08-05 03:24:41
【问题描述】:

我正在尝试用 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.Diagnostics.Stopwatch?你需要它真的很轻吗?你知道float 在精度方面的局限性和问题吗?

标签: c# time timing timedelta


【解决方案1】:

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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-27
    • 1970-01-01
    • 1970-01-01
    • 2011-02-06
    • 2014-12-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多