C#无法计算增量时间

时间:2015-08-05 03:24:41

标签: c# time timing timedelta

我正在尝试为用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计数似乎正常,但增量时间似乎比应有的快。

任何帮助表示赞赏。 :)

1 个答案:

答案 0 :(得分:2)

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