encompass-cs-docs/content/pong/move_paddle/frame_dependence.md

2.8 KiB

title date weight
Frame-Dependence 2019-05-23T14:12:20-07:00 20

Let's do a little experiment. In the PongFEGame constructor, add the following line:

    ...
    
    graphics.SynchronizeWithVerticalRetrace = false;

    ...

    IsFixedTimeStep = false;

    ...

This means that the game will now run with an unlocked timestep. In other words, the game will update as fast as the computer allows us to. By default, FNA tries to make the game update at a rate of 60 times per second, and synchronize with the monitor's refresh rate.

Now what happens if we run the game?

oh dear

Oh dear. That doesn't seem right at all. The paddle is moving way too fast. But our speed value is only 10. What's going on?

Remember when I mentioned frame-dependence and delta-time earlier? This is a classic example of frame-dependence. What's our framerate right now?

System.Console.WriteLine(1 / gameTime.ElapsedGameTime.TotalSeconds);

When I run the game, my console shows that the game is fluctuating at around 19000 frames per second. Our motion message when we press the down arrow key on the keyboard tells the paddle to move 10 units.

That means every frame we have the Down key held down, the paddle is moving 10 units. Which means, as things stand right now, the paddle is moving about 190,000 units per second. And if the framerate changes for some reason, the paddle will move slower or quicker. This means the actual progress of the simulation will be completely different on slower or faster computers.

Even if you use fixed timestep, what if you want to lock the timestep to 30 later? Or 120? The entire behavior of your game will change.

This is where delta-time comes in to save the day.

delta-time, as I mentioned before, is the amount of time that has passed between the previous frame and the current frame.

If we multiply the rate of change of the position by delta-time, then the paddle will move at the same speed no matter whether the framerate changes.

Let's go back to the line of the InputEngine where we send the MotionMessage.

    SendMessage(new MotionMessage(
        playerInputEntity,
        new System.Numerics.Vector2(0, 10 * (float)dt))
    );

better

Our simulation is now frame-independent, which is what we desire. The paddle is definitely moving too slowly now, but that's something we can fix with a bit of value tweaking.

It is very important that you take care to multiply things that change over time by the delta-time value, or you risk elements of your game becoming frame-dependent.

Before we move on, let's reset the values we changed in PongFEGame.

```cs
    ...

    graphics.SynchronizeWithVerticalRetrace = true;

    ...

    IsFixedTimeStep = true;

    ...