Skip to content

Chapter 04: Input and Frame Time ​

In Chapter 03: The Service Pattern and the Arena, you built ArenaSystem and learned the rhythm of contract card, stub, test and body. The cyan dot still sits at the corner of the arena, because nothing yet reads the keyboard.

In this chapter, you read the keyboard and gamepad once per frame into one value, and turn it into movement that is the same speed on every machine. You also write the first version of MovementSystem.

Figure 04-1: The chapter 04 window. The dot has moved along the top edge of the arena while the Right arrow was held
Figure 04-1: The chapter 04 window. The dot has moved along the top edge of the arena while the Right arrow was held. This is a drawn illustration, not a screenshot.

Time: [TODO Simon: time estimate for chapter 04]

In this chapter, you will:

  • Learn the difference between an input that is held and one that was just pressed.
  • Write InputState, a value that is one frame's snapshot of every game action.
  • Write InputManager, with a small seam so that tests can feed it fake devices.
  • Learn why movement multiplies speed by the frame time.
  • Start MovementSystem with its first two operations.

Requirements in this chapter ​

IDShort name
INP-01Keyboard and gamepad mapping
INP-02Held and pressed actions
INP-03One immutable snapshot per frame
INP-04Dead zone and trigger threshold
MOV-01Continuous movement at 150 px per second
MOV-02Cardinal only, with a fixed priority

Held and pressed ​

A key has two different meanings in a game. Sometimes the question is "is the key down right now?". That is a held state. Holding Right keeps the dot moving, so movement asks about the held state on every frame.

Sometimes the question is "did the key go down this frame?". That is a pressed edge. A menu choice must happen once for each press, even if the player holds the key for half a second. A pressed edge is true when the key is down now and was up on the previous frame. Figure 04-2 shows ten frames of one key, and what each kind of question answers on each frame.

Figure 04-2: Ten frames of one key. A held question is true for as long as the key is down. A pressed question is true for one frame only
Figure 04-2: Ten frames of one key. A held question is true for as long as the key is down. A pressed question is true for one frame only

The edge needs memory. To know that the key was up last frame, the input code must keep the previous frame's state. This is why InputManager stores the keyboard and gamepad state each time it is asked, and why you must ask it exactly once per frame. A second call in the same frame would compare the state with itself and turn every edge to false.

Actions, not keys ​

The rules of the game never ask which key is down. They ask whether the player is moving left, or has pressed confirm. InputState names the twelve actions the game understands, and InputManager is the only code that knows which key or button produces each one. A change of key binding then touches one file. A test can also build an InputState by hand, with no keyboard at all.

Why a value type ​

InputState is a readonly record struct. A struct is a value type: it is copied instead of referenced, and it is not allocated on the heap. The game takes a new snapshot every frame, 60 times a second, so a class would create 60 short-lived objects each second for the garbage collector to clean up. A struct costs none of that.

The word readonly means that no code can change a snapshot once it exists. Every property has an init setter, so it can be set only while the snapshot is being built. This is INP-03. One frame produces one snapshot, and every system that reads it sees the same values.

Frame time ​

A game redraws many times a second, and each redraw is one frame. If the dot moved a fixed number of pixels per frame, a computer that runs 30 frames a second would move it half as far as one that runs 60. The game would play at different speeds on different machines.

The fix is to measure speed in pixels per second and multiply by the time the frame took. That time is deltaTime, in seconds. Speed times time is distance. At 150 pixels per second, a 60 frames per second machine moves 2.5 pixels each frame and a 30 frames per second machine moves 5 pixels each frame. After one tenth of a second, both have moved 15 pixels. Figure 04-3 shows the comparison.

With the fixed time step from Chapter 01: The Project and the Host, ElapsedGameTime is 1/60 of a second on every update. It is not exactly 1/60 of a second when the fixed time step is off, or when an update runs late. In the late case, MonoGame catches up with extra updates, not fewer.

Figure 04-3: The same 0.1 seconds at two frame rates. Multiplying by deltaTime gives the same distance. A fixed step per frame does not
Figure 04-3: The same 0.1 seconds at two frame rates. Multiplying by deltaTime gives the same distance. A fixed step per frame does not

A seam for tests ​

Reading the real keyboard makes a test impossible to repeat, because the test would depend on what the person at the desk is pressing. A seam is a place where you can swap a real dependency for a fake one. InputManager takes two optional functions, one that returns a KeyboardState and one that returns a GamePadState. The game passes nothing and gets the real devices. A test passes functions that return fixed states, and can change those states between frames to script a key press.

Building the input state ​

Open a terminal in the LastPerimeter folder. Run the following command from there. The Source/Data and Source/Systems folders already exist.

text
mkdir Source/Input

In the Source/Input folder, create a new file named InputState.cs and add the following code. The four movement properties and the slow-draw property are held states. The other seven are pressed edges.

new-file Source/Input/InputState.cs
csharp
namespace LastPerimeter.Input;

// A value type: a new snapshot is taken every frame, so a struct avoids a heap
// allocation per frame.
public readonly record struct InputState
{
    public bool IsMovingUp { get; init; }
    public bool IsMovingDown { get; init; }
    public bool IsMovingLeft { get; init; }
    public bool IsMovingRight { get; init; }
    public bool IsSlowDrawHeld { get; init; }
    public bool IsConfirmPressed { get; init; }
    public bool IsCancelPressed { get; init; }
    public bool IsPausePressed { get; init; }
    public bool IsMenuUpPressed { get; init; }
    public bool IsMenuDownPressed { get; init; }
    public bool IsMenuLeftPressed { get; init; }
    public bool IsMenuRightPressed { get; init; }

    public static InputState Empty { get; } = new();
}

The key things to note are:

  • readonly record struct gives you a value type that compares by value and cannot change after it is built.
  • Each property has init, so a snapshot is filled in once, when InputManager creates it.
  • Empty is a snapshot in which nothing is pressed. Tests use it as the "player does nothing" input.
  • The names IsMovingUp and IsConfirmPressed say whether the action is held or a pressed edge. The name tells you which kind of question it answers.

Building the input manager ​

InputManager has one operation, GetCurrentInput. It turns the devices into an InputState.

InputManager.GetCurrentInput(playerIndex) : InputState

  • Takes: the player index, which defaults to player one.
  • Gives: one InputState for this frame.
  • Promises: movement and slow draw are held states. Confirm, cancel, pause and the menu moves are pressed edges, true on the first frame only. A thumbstick inside the dead zone of 0.2 does not move the player. The slow-draw trigger needs a pull of more than 0.35.
  • Refuses: nothing. With no keys down, the result equals InputState.Empty.
  • Requirements: INP-01, INP-02, INP-03, INP-04.

In the Source/Input folder, create a new file named InputManager.cs and add the following code. The two Func fields hold the optional device readers. New to Func? See the C# primer. The constructor and the fields are written in full. GetCurrentInput is a stub.

new-file Source/Input/InputManager.cs
csharp
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;

namespace LastPerimeter.Input;

public sealed class InputManager
{
    private const float ThumbstickDeadzone = 0.2f;
    private readonly Func<KeyboardState>? _readKeyboard;
    private readonly Func<GamePadState>? _readGamePad;
    private KeyboardState _previousKeyboardState;
    private GamePadState _previousGamePadState;

    // Pass device readers to feed fixed states (tests). With none, the real devices are read.
    public InputManager(Func<KeyboardState>? keyboard = null, Func<GamePadState>? gamePad = null)
    {
        _readKeyboard = keyboard;
        _readGamePad = gamePad;
    }

    public InputState GetCurrentInput(PlayerIndex playerIndex = PlayerIndex.One)
    {
        throw new NotImplementedException();
    }
}

The key things to note are:

  • _readKeyboard and _readGamePad hold the optional functions. When one is null, the real device is read.
  • _previousKeyboardState and _previousGamePadState are the memory that a pressed edge needs.
  • ThumbstickDeadzone is the 0.2 from the card. A thumbstick rests slightly off centre on many gamepads, so tiny values must count as zero.

In a terminal, from the LastPerimeter folder, run dotnet build. The build should succeed, which proves the stub compiles. Expect two warnings about unused fields, _previousKeyboardState and _previousGamePadState, until the body is written.

Now the tests. There is one for each of the two behaviours that a screenshot cannot show. In the Tests/Systems folder, create a new file named InputManagerTests.cs and add the following code.

PressedEdge_IsTrueForOneFrameOnly holds Enter down for two frames, releases it for one frame, then presses it again. The test passes a variable to the seam, so changing the variable changes what the keyboard reports. The () => keyboard that does this is a closure. New to closures? See the C# primer. Thumbstick_InsideDeadZone_DoesNotMove builds one gamepad with a stick pushed 0.1 to the right and one pushed 0.5, and checks that only the second moves.

new-file Tests/Systems/InputManagerTests.cs
csharp
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using LastPerimeter.Input;

namespace LastPerimeter.Tests.Systems;

public sealed class InputManagerTests
{
    [Fact]
    public void PressedEdge_IsTrueForOneFrameOnly()
    {
        KeyboardState keyboard = new(Keys.Enter);
        InputManager input = new(() => keyboard, () => default);

        InputState first = input.GetCurrentInput();
        InputState second = input.GetCurrentInput();
        keyboard = default;
        input.GetCurrentInput();
        keyboard = new KeyboardState(Keys.Enter);
        InputState third = input.GetCurrentInput();

        Assert.True(first.IsConfirmPressed);
        Assert.False(second.IsConfirmPressed);
        Assert.True(third.IsConfirmPressed);
    }

    [Fact]
    public void Thumbstick_InsideDeadZone_DoesNotMove()
    {
        GamePadState small = Stick(0.1f);
        GamePadState large = Stick(0.5f);

        InputState quiet = new InputManager(() => default, () => small).GetCurrentInput();
        InputState moving = new InputManager(() => default, () => large).GetCurrentInput();

        Assert.False(quiet.IsMovingRight);
        Assert.True(moving.IsMovingRight);
    }

    private static GamePadState Stick(float x)
    {
        return new GamePadState(new GamePadThumbSticks(new Vector2(x, 0f), Vector2.Zero), new GamePadTriggers(), new GamePadButtons(), new GamePadDPad());
    }
}

In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 2 and Passed: 10. The 10 passes are the tests from earlier chapters. Both new tests fail on the stub.

The body needs two small helpers, so add them first. Both are named WasPressed. One compares two keyboard states for a key. The other compares two button states. A private helper has no card of its own. Open Source/Input/InputManager.cs. Add the following methods to the InputManager class, below the GetCurrentInput method:

add-member Source/Input/InputManager.cs after=GetCurrentInput
csharp
    private static bool WasPressed(KeyboardState currentState, KeyboardState previousState, Keys key)
    {
        return currentState.IsKeyDown(key) && !previousState.IsKeyDown(key);
    }

    private static bool WasPressed(ButtonState currentState, ButtonState previousState)
    {
        return currentState == ButtonState.Pressed && previousState == ButtonState.Released;
    }

In the same file, find the GetCurrentInput method and replace the whole method with the following:

replace-method Source/Input/InputManager.cs GetCurrentInput
csharp
    public InputState GetCurrentInput(PlayerIndex playerIndex = PlayerIndex.One)
    {
        KeyboardState keyboard = _readKeyboard is null ? Keyboard.GetState() : _readKeyboard();
        GamePadState gamePad = _readGamePad is null ? GamePad.GetState(playerIndex) : _readGamePad();
        InputState inputState = new()
        {
            IsMovingUp = keyboard.IsKeyDown(Keys.Up) || gamePad.DPad.Up == ButtonState.Pressed || gamePad.ThumbSticks.Left.Y > ThumbstickDeadzone,
            IsMovingDown = keyboard.IsKeyDown(Keys.Down) || gamePad.DPad.Down == ButtonState.Pressed || gamePad.ThumbSticks.Left.Y < -ThumbstickDeadzone,
            IsMovingLeft = keyboard.IsKeyDown(Keys.Left) || gamePad.DPad.Left == ButtonState.Pressed || gamePad.ThumbSticks.Left.X < -ThumbstickDeadzone,
            IsMovingRight = keyboard.IsKeyDown(Keys.Right) || gamePad.DPad.Right == ButtonState.Pressed || gamePad.ThumbSticks.Left.X > ThumbstickDeadzone,
            IsSlowDrawHeld = keyboard.IsKeyDown(Keys.Space) || keyboard.IsKeyDown(Keys.LeftShift) || gamePad.Triggers.Right > 0.35f || gamePad.Buttons.A == ButtonState.Pressed,
            IsConfirmPressed = WasPressed(keyboard, _previousKeyboardState, Keys.Enter) || WasPressed(keyboard, _previousKeyboardState, Keys.Space) || WasPressed(gamePad.Buttons.A, _previousGamePadState.Buttons.A),
            IsCancelPressed = WasPressed(keyboard, _previousKeyboardState, Keys.Back) || WasPressed(keyboard, _previousKeyboardState, Keys.Escape) || WasPressed(gamePad.Buttons.B, _previousGamePadState.Buttons.B),
            IsPausePressed = WasPressed(keyboard, _previousKeyboardState, Keys.Escape) || WasPressed(gamePad.Buttons.Start, _previousGamePadState.Buttons.Start),
            IsMenuUpPressed = WasPressed(keyboard, _previousKeyboardState, Keys.Up) || WasPressed(gamePad.DPad.Up, _previousGamePadState.DPad.Up),
            IsMenuDownPressed = WasPressed(keyboard, _previousKeyboardState, Keys.Down) || WasPressed(gamePad.DPad.Down, _previousGamePadState.DPad.Down),
            IsMenuLeftPressed = WasPressed(keyboard, _previousKeyboardState, Keys.Left) || WasPressed(gamePad.DPad.Left, _previousGamePadState.DPad.Left),
            IsMenuRightPressed = WasPressed(keyboard, _previousKeyboardState, Keys.Right) || WasPressed(gamePad.DPad.Right, _previousGamePadState.DPad.Right),
        };

        _previousKeyboardState = keyboard;
        _previousGamePadState = gamePad;
        return inputState;
    }

In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 0 and Passed: 12.

The key things to note are:

  • The method reads both devices once, builds the InputState, and only then stores the states as the new previous states. The edge checks must see the old previous states, so the store comes last.
  • A held state is one IsKeyDown or button check. A pressed edge calls WasPressed, which needs the current and the previous state.
  • Each action is the || of a keyboard key and a gamepad control. This is INP-01. The arrow keys, the d-pad and the left stick all move the player.
  • Space gives both IsSlowDrawHeld and IsConfirmPressed, and Escape gives both cancel and pause. One key can answer more than one action, and each scene reads only the ones it cares about.
  • The stick uses > ThumbstickDeadzone and < -ThumbstickDeadzone. Up reads ThumbSticks.Left.Y > ThumbstickDeadzone because a gamepad reports up as positive.
  • The slow-draw trigger threshold of 0.35 has no test of its own in this chapter. You see it work when slow draw arrives in a later chapter.

NOTE

PressedEdge_IsTrueForOneFrameOnly is the proof of INP-02. It would fail if GetCurrentInput stored the previous state before it built the snapshot, or if it never stored it.

Building the movement system ​

MovementSystem turns an InputState into a direction, and a direction into a new position. It holds no state, so it needs no constructor. You write the two operations in turn.

In the Source/Systems folder, create a new file named MovementSystem.cs and add the following code. Both operations are stubs. The file already refers to Direction, which exists from Chapter 03, and to Vector2.

new-file Source/Systems/MovementSystem.cs
csharp
using Microsoft.Xna.Framework;
using LastPerimeter.Data;
using LastPerimeter.Input;

namespace LastPerimeter.Systems;

public sealed class MovementSystem
{
    public Direction DetermineDirection(InputState inputState)
    {
        throw new NotImplementedException();
    }

    public Vector2 CalculateNextPosition(Vector2 currentPosition, Direction direction, float speed, float deltaTime)
    {
        throw new NotImplementedException();
    }
}

Choosing a direction ​

The player moves along one axis at a time. The wall and the trail you build in later chapters are made of horizontal and vertical segments, so a diagonal step could never stay on one. When two keys are held, a fixed priority decides: left, then right, then up, then down.

MovementSystem.DetermineDirection(inputState) : Direction

  • Takes: one InputState.
  • Gives: Left, Right, Up, Down or None.
  • Promises: at most one direction. The priority is left, right, up, down. Horizontal wins over vertical.
  • Refuses: nothing. When no movement is held, the result is None.
  • Requirements: MOV-02.

In the Tests/Systems folder, create a new file named MovementSystemTests.cs and add the following code. The first test gives no input and expects None. The second holds two keys at a time and checks which one wins.

new-file Tests/Systems/MovementSystemTests.cs
csharp
using LastPerimeter.Data;
using LastPerimeter.Input;
using LastPerimeter.Systems;

namespace LastPerimeter.Tests.Systems;

public sealed class MovementSystemTests
{
    [Fact]
    public void DetermineDirection_WithNoInput_ReturnsNone()
    {
        MovementSystem movementSystem = new();

        Direction direction = movementSystem.DetermineDirection(InputState.Empty);

        Assert.Equal(Direction.None, direction);
    }

    [Fact]
    public void DetermineDirection_PrefersHorizontal()
    {
        MovementSystem movement = new();

        Assert.Equal(Direction.Left, movement.DetermineDirection(new InputState { IsMovingLeft = true, IsMovingUp = true }));
        Assert.Equal(Direction.Left, movement.DetermineDirection(new InputState { IsMovingLeft = true, IsMovingRight = true }));
        Assert.Equal(Direction.Right, movement.DetermineDirection(new InputState { IsMovingRight = true, IsMovingDown = true }));
    }
}

In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 2 and Passed: 12.

Open Source/Systems/MovementSystem.cs. Find the DetermineDirection method and replace the whole method with the following:

replace-method Source/Systems/MovementSystem.cs DetermineDirection
csharp
    public Direction DetermineDirection(InputState inputState)
    {
        if (inputState.IsMovingLeft) return Direction.Left;
        if (inputState.IsMovingRight) return Direction.Right;
        if (inputState.IsMovingUp) return Direction.Up;
        if (inputState.IsMovingDown) return Direction.Down;
        return Direction.None;
    }

Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 0 and Passed: 14.

The key things to note are:

  • The checks run in priority order, and each return ends the method. This is why Left beats Up, and why Left beats Right when both are held.
  • The method looks only at the held states. It never reads a pressed edge.
  • The test checks three pairs, one of each kind: left with up, left with right, and right with down.

Calculating the next position ​

The second operation applies the frame-time rule from Figure 04-3. It needs the unit vector of a direction, which is a vector of length one that points that way. You add that first, as a small set of helpers on Direction.

Open Source/Data/Enums.cs. Add the following class to the file, directly below the Direction enum and above TrailState. Do not change the enums. The direction switch in each method is a switch expression. New to those? See the C# primer. ToVector gives (0, -1) for Up, because the screen's y axis points down. Opposite gives the reverse direction, which later chapters use. It has no test of its own in this chapter.

add-type Source/Data/Enums.cs after=Direction
csharp
public static class DirectionExtensions
{
    public static Direction Opposite(this Direction direction) => direction switch
    {
        Direction.Up => Direction.Down,
        Direction.Down => Direction.Up,
        Direction.Left => Direction.Right,
        Direction.Right => Direction.Left,
        _ => Direction.None,
    };

    public static Microsoft.Xna.Framework.Vector2 ToVector(this Direction direction) => direction switch
    {
        Direction.Up => new Microsoft.Xna.Framework.Vector2(0f, -1f),
        Direction.Down => new Microsoft.Xna.Framework.Vector2(0f, 1f),
        Direction.Left => new Microsoft.Xna.Framework.Vector2(-1f, 0f),
        Direction.Right => new Microsoft.Xna.Framework.Vector2(1f, 0f),
        _ => Microsoft.Xna.Framework.Vector2.Zero,
    };
}

The key things to note are:

  • An extension method is a static method whose first parameter has this. It lets you write direction.ToVector() as if the enum had that method. New to extension methods? See the C# primer.
  • After this change the types in Enums.cs are in this order: Direction, DirectionExtensions, TrailState, TileState. Check that your file has the same order.
  • Enums.cs has no using for MonoGame, so the listing writes Microsoft.Xna.Framework.Vector2 in full.
  • None and any other value give Vector2.Zero, so a None direction never moves the player.

MovementSystem.CalculateNextPosition(currentPosition, direction, speed, deltaTime) : Vector2

  • Takes: a position, a direction, a speed in pixels per second and the frame time in seconds.
  • Gives: the position after one frame.
  • Promises: the result is the position plus the direction's unit vector times speed times time. Half the time gives half the distance.
  • Refuses: nothing. Direction.None returns the position unchanged. The method does not check the arena. The caller clamps the result.
  • Requirements: MOV-01.

The stub is already in your file. Open Tests/Systems/MovementSystemTests.cs. At the top of the file, add the following line above the other using lines. The test builds a Vector2, which lives in the Microsoft.Xna.Framework namespace.

add-using Tests/Systems/MovementSystemTests.cs before=LastPerimeter.Data
csharp
using Microsoft.Xna.Framework;

Add the following test to the MovementSystemTests class, below the DetermineDirection_PrefersHorizontal test. It moves a point at 100 pixels per second for half a second, then for a quarter of a second.

add-member Tests/Systems/MovementSystemTests.cs after=DetermineDirection_PrefersHorizontal
csharp
    [Fact]
    public void CalculateNextPosition_ScalesWithDeltaTime()
    {
        MovementSystem movement = new();

        Vector2 half = movement.CalculateNextPosition(Vector2.Zero, Direction.Right, 100f, 0.5f);
        Vector2 quarter = movement.CalculateNextPosition(Vector2.Zero, Direction.Right, 100f, 0.25f);

        Assert.Equal(new Vector2(50f, 0f), half);
        Assert.Equal(new Vector2(25f, 0f), quarter);
    }

In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 1 and Passed: 14.

Open Source/Systems/MovementSystem.cs. Find the CalculateNextPosition method and replace the whole method with the following:

replace-method Source/Systems/MovementSystem.cs CalculateNextPosition
csharp
    public Vector2 CalculateNextPosition(Vector2 currentPosition, Direction direction, float speed, float deltaTime)
    {
        return currentPosition + (direction.ToVector() * speed * deltaTime);
    }

Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 0 and Passed: 15.

The key things to note are:

  • The whole rule is one line: position plus direction times speed times time.
  • The test uses a speed of 100 so that the answers, 50 and 25, can be checked by eye. It proves that the distance scales with deltaTime, as in Figure 04-3.
  • Multiplying a Vector2 by a float scales both parts, so a Left direction moves along x only and the y part stays zero.
  • The method never clamps. Keeping the arena rule out of it means that the same movement code works for the player now and for other moving things later.

Wiring it into the game ​

The player must now move. You add the speed to GameConfig, then make three changes to the host.

Open Source/Data/GameConfig.cs. Add the following property to the GameConfig record, below the TileSize property. The 150 is MOV-01. It sits in the config, with the other tuning numbers, so that a test or a later difficulty setting can change it.

add-member Source/Data/GameConfig.cs after=TileSize
csharp
    public float PlayerSpeed { get; init; } = 150f;

Open Source/Game/LastPerimeterApp.cs. At the top of the file, add the following lines below the using LastPerimeter.Entities; line:

add-using Source/Game/LastPerimeterApp.cs after=LastPerimeter.Entities
csharp
using LastPerimeter.Input;
using LastPerimeter.Systems;

Add the following field to the LastPerimeterApp class, below the _config field:

add-member Source/Game/LastPerimeterApp.cs after=_config
csharp
    private readonly InputManager _input = new();

Add the following field below the _input field:

add-member Source/Game/LastPerimeterApp.cs after=_input
csharp
    private readonly MovementSystem _movement = new();

In the same file, find the Update method and replace the whole method with the following:

replace-method Source/Game/LastPerimeterApp.cs Update
csharp
    protected override void Update(GameTime gameTime)
    {
        if (ShouldAutoExit(gameTime))
        {
            return;
        }

        // A first version of movement in the host. Chapter 05 moves all of this into the simulation.
        InputState input = _input.GetCurrentInput();
        float deltaTime = (float)gameTime.ElapsedGameTime.TotalSeconds;
        Direction direction = _movement.DetermineDirection(input);
        Vector2 next = _movement.CalculateNextPosition(_player.Position, direction, _config.PlayerSpeed, deltaTime);
        Rectangle bounds = _config.ArenaBounds;
        _player.Position = new Vector2(Math.Clamp(next.X, bounds.Left, bounds.Right), Math.Clamp(next.Y, bounds.Top, bounds.Bottom));

        base.Update(gameTime);
    }

The key changes are:

  • Update reads the input once, with _input.GetCurrentInput(). This is the single call per frame that Figure 04-2 depends on.
  • deltaTime is the elapsed game time in seconds, taken from gameTime.ElapsedGameTime.TotalSeconds. MonoGame calls Update 60 times a second by default, so it is about 0.0167.
  • The player's new position is clamped to the arena rectangle with Math.Clamp, so the dot can reach an edge but never cross it.
  • The comment is honest. The host now holds game rules, which it should not. This is deliberate, so that you feel the problem before Chapter 05: Scenes and the Gameplay Simulation solves it.

Running the tests ​

In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 0 and Passed: 15. The 15 tests are the 10 from earlier chapters and the 5 new ones.

TestProves
PressedEdge_IsTrueForOneFrameOnlyINP-02
Thumbstick_InsideDeadZone_DoesNotMoveINP-04, and the thumbstick part of INP-01
DetermineDirection_WithNoInput_ReturnsNoneMOV-02
DetermineDirection_PrefersHorizontalMOV-02
CalculateNextPosition_ScalesWithDeltaTimeMOV-01

INP-03 is a property of the type. Because InputState is a readonly record struct, the compiler refuses any code that changes a snapshot. The rest of INP-01 is the mapping in GetCurrentInput, and you prove it by hand in the next section.

Running the game ​

The movement checks below need a window and a keyboard, so only you can confirm them. The test count above proves the rules behind them without either.

From the LastPerimeter folder, run dotnet run --project Platforms/DesktopVK. A window opens with the arena and the cyan dot at its top-left corner. Do the following, in order:

  • Hold the Right arrow. The dot moves right along the top edge at a steady speed. It crosses the 924 pixel arena in about six seconds, and it stops at the right edge.
  • Release Right. The dot stops at once.
  • Hold Down. The dot moves down the right edge and stops at the bottom corner.
  • Hold Left and Up together. The dot moves left only, because horizontal wins.
  • Hold Up until the dot reaches the top edge. Then hold Up and Right together. The dot moves right only, because horizontal wins.

If you have a gamepad connected, push the left stick a little. The dot stays still inside the dead zone and moves once you push further. Close the window with its close button.

The next section is optional. It replaces your files with the chapter 04 snapshot.

If you got lost ​

This section is optional. Use it only when your project no longer builds or the tests no longer match this chapter. It overwrites your Source and Tests folders with the chapter 04 snapshot, so any change of your own in those folders is lost. <course-repo> is the folder where you cloned the course repository.

WARNING

These commands overwrite your own changes in Source and Tests. Copy your project folder elsewhere first if you want to keep it.

In PowerShell, from the LastPerimeter folder, run the following. Replace <course-repo> with the real path first.

powershell
$snapshot = "<course-repo>/DOCUMENTATION/learning_plan_2/snapshots/04-Input-And-Frame-Time"
Remove-Item -Recurse -Force Source, Tests
Copy-Item -Recurse "$snapshot/Source" Source
Copy-Item -Recurse "$snapshot/Tests" Tests

In bash, from the LastPerimeter folder, run the following. Replace <course-repo> with the real path first.

bash
snapshot="<course-repo>/DOCUMENTATION/learning_plan_2/snapshots/04-Input-And-Frame-Time"
rm -rf Source Tests
cp -r "$snapshot/Source" Source
cp -r "$snapshot/Tests" Tests

Then run dotnet test from the LastPerimeter folder and check for Passed: 15.

Common mistakes ​

  • The dot does not move at all. The Update method in the host does not call _input.GetCurrentInput(), or it was not saved. Check that the new lines sit above base.Update(gameTime);.
  • A pressed edge stays true for many frames. GetCurrentInput does not store the previous states, or it stores them before it builds the snapshot. The store must come last.
  • The dot moves much faster or slower than expected. deltaTime is in milliseconds or is missing. Use TotalSeconds, and check that PlayerSpeed is 150.
  • The dot moves up when you hold Down. The unit vectors are the wrong way round. The screen's y axis points down, so Up is (0, -1) and Down is (0, 1).
  • The build says Direction has no ToVector. The DirectionExtensions class is missing from Enums.cs, or it is in a different namespace. It belongs in the same file as the enum.

Conclusion ​

In this chapter, you accomplished the following:

The tests now prove INP-02, INP-04, MOV-01 and MOV-02, and the type proves INP-03. You checked INP-01 by running the game. In the next chapter, Chapter 05: Scenes and the Gameplay Simulation, you move the movement code out of the host into a simulation that runs with no window.

Test Your Knowledge ​

  1. Why must GetCurrentInput be called exactly once per frame?

    Answer

    It stores this frame's state for the next frame's edge checks. A second call in the same frame would compare the state with itself, and a pressed edge would turn false.

  2. Holding Left and Up gives Left. Why does the game choose one direction instead of moving diagonally?

    Answer

    The wall and the trail are made of horizontal and vertical segments. A diagonal move could never stay on a segment, so the game allows one axis at a time and uses a fixed priority when two keys are held.

  3. What would a player on a slow machine notice if movement ignored deltaTime?

    Answer

    It depends on the time step. With the fixed time step from Chapter 01, MonoGame calls Update 60 times a second and catches up with extra updates when a frame runs long. The dot would then keep the same speed. With the fixed time step off, Update runs once per frame, so a slow machine runs it fewer times and the dot moves more slowly. Multiplying by deltaTime gives the right speed in both cases.

  4. Why does InputManager take two optional functions in its constructor?

    Answer

    The functions are a seam. The game passes nothing and reads the real devices, and a test passes fixed states. This makes a pressed edge and the dead zone testable without a keyboard.

Extensions ​

  • Add a test that holds Space and checks that IsSlowDrawHeld is true for every frame, while IsConfirmPressed is true for the first frame only. This shows the held and pressed kinds side by side.
  • Change PlayerSpeed in GameConfig to 300 and run the game. The dot should cross the arena in about half the time. Change it back to 150.