Appearance
Chapter 03 - Input, Timing, and Player Movement
Where this chapter fits: the player dot finally moves. Input is read every frame, turned into one cardinal direction, and applied as time-based motion. Movement is still free inside the arena; constraining it to the wall is chapter 04.
Time: [TODO Simon: time estimate for chapter 03]
Free movement in the chapter 03 build: after holding Right and then Down, the dot has left the centre and can roam anywhere inside the frame.
Prerequisites
Chapters 01-02 (render loop, GameConfig, ArenaSystem, GameSession). You should know what GameTime.ElapsedGameTime is from chapter 01.
Learning objectives
By the end of this chapter you should be able to:
- build a per-frame input snapshot from keyboard and gamepad, including deadzone handling and edge detection,
- explain the difference between a held flag and a pressed-this-frame flag, and say which one movement uses,
- convert raw input into a single cardinal
Directionand state the priority order, - compute time-based displacement and defend it against the pixels-per-frame alternative,
- clamp free movement to the arena bounds,
- articulate the difference between free movement (this chapter) and path-constrained movement (next chapter).
Code anchors
Source/Input/InputManager.csSource/Input/InputState.csSource/Systems/MovementSystem.csSource/Data/Enums.csSource/Game/LastPerimeterApp.cs(chapter 03 staged version: free movement with a clamp)
The three-stage movement model
Think of movement as three clean stages: read input every frame, convert input into a direction, convert direction into legal motion. That separation keeps later systems understandable, because chapter 04 replaces only the third stage.
Stage 1 - The input snapshot
MonoGame does not deliver key events. Instead it lets you poll the current state of every key and button. InputManager.GetCurrentInput polls once per frame and packs the result into an immutable value type. A new snapshot is taken every frame, so a struct avoids a heap allocation per frame:
csharp
// 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();
}There are two kinds of flag in that record, and the difference is the most important idea in the chapter:
IsMoving*andIsSlowDrawHeldare held flags: true on every frame the key is down. Movement wants this: hold Right, keep moving.Is*Pressedare edge flags: true only on the frame the key went down, computed by comparing with the previous frame's state. Menus and confirmations want this: one press, one action.
The manager builds both from the same two polls:
csharp
public sealed class InputManager
{
private const float ThumbstickDeadzone = 0.2f;
private KeyboardState _previousKeyboardState;
private GamePadState _previousGamePadState;
public InputState GetCurrentInput(PlayerIndex playerIndex = PlayerIndex.One)
{
KeyboardState keyboard = Keyboard.GetState();
GamePadState gamePad = GamePad.GetState(playerIndex);
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;
}
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;
}
}The two WasPressed overloads are the same edge test for keys and for gamepad buttons. Without the ButtonState overload the gamepad lines above do not compile.
Three details to notice:
- the analogue stick reports
-1..1on each axis; the deadzone of0.2ignores the small wobble a resting stick produces. Note that the stick's Y axis is positive upward, the opposite of screen space, which is whyIsMovingUptests> ThumbstickDeadzone, - the whole snapshot is rebuilt every frame and never accumulated, which is what fixes the classic "tap to move one step" bug,
- storing only the previous frame's raw state is enough for edge detection; there is no event queue to drain.
Controls
This table is the one place to look for every control in the course. Only movement and closing the game work in this chapter. The last column says where each of the others arrives.
| Action | Keyboard | Gamepad | Arrives in |
|---|---|---|---|
| Move | arrow keys | D-pad or left stick | chapter 03 |
| Close the game | Escape | Back | chapters 01-11 |
| Slow draw (hold) | Space or Left Shift | right trigger or A | chapter 08 |
| Confirm | Enter or Space | A | chapter 10 |
| Pause | Escape | Start | chapter 12 |
| Cancel or go back | Backspace or Escape | B | chapter 12 |
| Move through menus | arrow keys | D-pad | chapter 12 |
Stage 2 - Why directions are cardinal
The game intentionally uses only up, down, left and right, with no diagonals. This is a design choice, not a limitation. It simplifies wall traversal, trail creation, collision reasoning, and player readability.
MovementSystem.DetermineDirection picks exactly one direction with a fixed priority, so holding two keys is never ambiguous:
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;
}The priority order is Left, Right, Up, Down.
Stage 3 - Time-based displacement
The movement equation is displacement = velocity * deltaTime, and MovementSystem.CalculateNextPosition is exactly that:
csharp
public Vector2 CalculateNextPosition(Vector2 currentPosition, Direction direction, float speed, float deltaTime)
{
return currentPosition + (direction.ToVector() * speed * deltaTime);
}With PlayerSpeed = 150 px/s and MonoGame's 60 Hz fixed step (deltaTime about 0.0167 s) the player moves 2.5 px per frame. On a machine that only manages 30 FPS, MonoGame calls Update twice per drawn frame to keep the simulation at 60 Hz. The displacement per real second is unchanged. Code that moves 2.5 px per Update is also safe under the fixed step. But if IsFixedTimeStep is turned off, or a frame is dropped, pixels-per-frame code drifts. Multiplying by deltaTime is correct in both worlds, so the course does it from the first moving object.
The MovementSystem.cs you copy for this chapter already contains TryMoveAlongPath as well. It goes unused until chapter 04, which explains it and makes movement path-constrained.
Build it step by step
This chapter is copy-along. Step 1 copies the chapter's files from the snapshot, and the steps after it walk through what changed and why. The listings in this chapter show the parts worth studying, not every line.
Step 1 - Copy the chapter files
From your LastPerimeter folder, copy the Source and Tests folders from this chapter's snapshot over your own. The command creates any folders you do not have yet and overwrites the files that changed. Replace <course-repo> with the path to your copy of the course repository (the course index explains how to get it).
In PowerShell:
powershell
Copy-Item -Recurse -Force "<course-repo>/DOCUMENTATION/LastPerimeter-Source/03-Input-Timing-And-Player-Movement/Source", "<course-repo>/DOCUMENTATION/LastPerimeter-Source/03-Input-Timing-And-Player-Movement/Tests" .In bash:
bash
cp -R "<course-repo>/DOCUMENTATION/LastPerimeter-Source/03-Input-Timing-And-Player-Movement/Source" "<course-repo>/DOCUMENTATION/LastPerimeter-Source/03-Input-Timing-And-Player-Movement/Tests" .That copy brings in these files:
New files:
Source/Input/InputManager.csSource/Input/InputState.csSource/Systems/MovementSystem.cs
Replaced files (the copy overwrites your versions):
Source/Game/LastPerimeterApp.cs
NOTE
Every step after this one describes code that is already in the files you just copied. Open the file each step names and read along. You type nothing unless a step says so.
Step 2 - Read the input and movement files
Open Source/Input/InputState.cs, Source/Input/InputManager.cs and Source/Systems/MovementSystem.cs, and match them against the listings above.
Step 3 - The game class: LastPerimeterApp (chapter 03 version)
Open Source/Game/LastPerimeterApp.cs. Initialize now constructs a MovementSystem and an InputManager next to the ArenaSystem. The body of Update (after the auto-exit and Escape checks) is the free-movement step:
csharp
float deltaTime = (float)gameTime.ElapsedGameTime.TotalSeconds;
InputState inputState = _inputManager.GetCurrentInput();
Direction direction = _movementSystem.DetermineDirection(inputState);
if (direction != Direction.None)
{
Vector2 candidate = _movementSystem.CalculateNextPosition(_gameSession.Player.Position, direction, _gameSession.Player.Speed, deltaTime);
_gameSession.Player.Position = ClampInsideArena(candidate, _arenaSystem.Bounds, _gameSession.Player.Radius);
_gameSession.Player.CurrentDirection = direction;
}The clamp helper keeps the whole circle inside the arena by shrinking the allowed range by the radius:
csharp
private static Vector2 ClampInsideArena(Vector2 position, Rectangle bounds, float radius)
{
return new Vector2(
MathHelper.Clamp(position.X, bounds.Left + radius, bounds.Right - radius),
MathHelper.Clamp(position.Y, bounds.Top + radius, bounds.Bottom - radius));
}Draw is unchanged from chapter 02. No new tests arrive; MovementSystemTests is staged in chapter 04 next to the wall path it exercises.
Step 4 - Build, test, run
Run these commands from the LastPerimeter folder:
bash
dotnet build
dotnet test
dotnet run --project Platforms/DesktopVKdotnet test reports 6 passing tests. On Windows you can also run dotnet run --project Platforms/WindowsDX12.
Chapter snapshot
The matching buildable project is DOCUMENTATION/LastPerimeter-Source/03-Input-Timing-And-Player-Movement; build and test it standalone with dotnet build and dotnet test. No new test files arrive in this chapter, so dotnet test should still report 6 passing tests (launch options and arena).
Checkpoint
- In your
LastPerimeterfolder, rundotnet test: 6 tests pass. If yours differ, compare your files with the snapshot inDOCUMENTATION/LastPerimeter-Source/03-Input-Timing-And-Player-Movement. - Run
dotnet run --project Platforms/DesktopVKand hold each arrow key in turn (or use the D-pad or left stick): the dot moves smoothly in all four directions. Hold Right until the dot stops: it stops exactly at the arena edge, as in the screenshot above. Press Escape to close the game. - Run the game again and hold Up and Left together: the dot moves left. Then open
Source/Systems/MovementSystem.csand find the lines inDetermineDirectionthat decide the priority order. - Open
Source/Systems/MovementSystem.csand, inCalculateNextPosition, replacespeed * deltaTimewith2.5f. Then openSource/Game/LastPerimeterApp.csand add_graphics.SynchronizeWithVerticalRetrace = false;andIsFixedTimeStep = false;as the last two lines of theLastPerimeterAppconstructor. Run the game and hold Right: the dot's speed now follows the frame rate, which is usually far above 60 without vertical sync, so it crosses the arena much faster. Then undo all three changes.
What you should have now
You now have:
- per-frame input capture,
- directional intent,
- free movement maths,
- a clamp that keeps the player inside the arena.
Common mistakes
- reading
Keyboard.GetState()in several places per frame (poll once, share the snapshot), - using the edge flag for movement (the player moves one step per press) or the held flag for menus (one press selects five rows),
- forgetting the deadzone, so a resting stick creeps the player sideways,
- forgetting that the stick's Y axis points up while the screen's points down,
- adding pixels per frame instead of pixels per second times
deltaTime.
Questions to think about
Compare these two:
CalculateNextPositionfor free-space movement,- path traversal methods for legal movement on a wall path.
NOTE
That distinction prepares you for the next chapter.

