Build a Godot game
The example connects movement, spawning, collisions, and scoring to typed UI, pause, and saves. Run the complete project first, then follow the wiring below.
Prepare the tools
Install the repository SDK and matching Godot .NET editor. Run the commands below from the repository root.
Build and launch
dotnet build Samples/DodgeTheCreeps/DodgeTheCreeps.csproj -c Debug
godot --headless --editor --path Samples/DodgeTheCreeps --import
godot --path Samples/DodgeTheCreepsAssets
See the asset credits and licenses. Keep the relevant notices and credits if you reuse assets.
Player movement
Use the native character to read directional input and play its animation.
/// <summary>Moves from the declared gameplay actions and updates the matching animation.</summary>
/// <param name="delta">Elapsed unpaused physics-frame time.</param>
internal void Advance(double delta)
{
_animationTime += delta;
var direction = Input.GetVector("dodge_left", "dodge_right", "dodge_up", "dodge_down");
Position = (Position + direction * (float)(330 * delta)).Clamp(
new Vector2(26, 82), new Vector2(454, 686));
if (direction.LengthSquared() <= 0)
{
_sprite.Stop();
}
else
{
// Input.GetVector limits the vector length to one, preserving equal maximum
// speed on cardinal and diagonal input while still allowing analog strengths.
FacingDirection = (Mathf.RoundToInt(direction.Angle() / (Mathf.Pi / 4)) + 8) % 8;
ApplyFacing();
_sprite.Play();
}
_sprite.Modulate = new Color(1, 1, 1,
_invulnerable ? 0.6f + 0.4f * Mathf.Abs(Mathf.Sin((float)_animationTime * 8)) : 1);
}Enemies, collisions, and scoring
Update enemies and scoring in the game loop. Close the current run's save when the game ends.
/// <summary>Advances native movement, enemy ownership, scoring, and collision detection in one frame.</summary>
/// <param name="delta">Elapsed unpaused physics-frame time.</param>
public override void _PhysicsProcess(double delta)
{
if (!IsRunning)
return;
_graceRemaining = Math.Max(0, _graceRemaining - delta);
_player.SetInvulnerable(_graceRemaining > 0);
_player.Advance(delta);
AdvanceScore(delta);
if (!IsRunning)
return;
_spawnRemaining -= delta;
if (_spawnRemaining <= 0)
{
SpawnCreep();
_spawnRemaining = Math.Max(0.30, (_arena?.SpawnInterval ?? 0.68) - Score * 0.003);
}
AdvanceCreeps(delta);
}private void AdvanceCreeps(double delta)
{
var hitDistance = DodgePlayer.HitRadius + DodgeMob.HitRadius;
for (var i = _mobs.Count - 1; i >= 0; i--)
{
var mob = _mobs[i];
mob.Advance(delta);
if (mob.Position.X < -125 || mob.Position.X > ArenaWidth + 125 ||
mob.Position.Y < -125 || mob.Position.Y > ArenaHeight + 125)
{
_mobs.RemoveAt(i);
mob.QueueFree();
continue;
}
if (_graceRemaining <= 0 &&
mob.Position.DistanceSquaredTo(_player.Position) < hitDistance * hitDistance)
{
EndRun();
return;
}
}
}Pages and windows
Define typed arguments and policies for the HUD, settings, and quit confirmation.
// Copyright (c) 2025-2026 GeWuYou
// SPDX-License-Identifier: Apache-2.0
using System;
using GFramework.Game.Abstractions.UI;
namespace DodgeTheCreeps;
/// <summary>Typed definitions shared by registration and business operations.</summary>
internal static class DodgeRoutes
{
/// <summary>Main menu navigation page.</summary>
internal static UiRoute<bool> Menu { get; } = new("menu", new UiRouteOptions { Layer = 10, AllowBack = false, BlocksWorldActionInput = true, BlocksWorldPointerInput = true });
/// <summary>Gameplay HUD stays visible under menus without owning input.</summary>
internal static UiRoute<int> Hud { get; } = new("hud", new UiRouteOptions { Kind = UiRouteKind.Window, Layer = 5, AllowBack = false, CapturedActions = UiInputActionMask.None });
/// <summary>Gameplay pause window owns one pause request.</summary>
internal static UiRoute<int> Pause { get; } = new("pause", Modal(20));
/// <summary>Settings owns a separate pause request, including while opened over pause.</summary>
internal static UiRoute<bool> Settings { get; } = new("settings", Modal(30));
/// <summary>Unsaved settings use an explicit apply, discard or keep-editing result.</summary>
internal static UiDialogRoute<bool, SettingsCloseChoice> SettingsUnsaved { get; } = new("settings-unsaved", Modal(40));
/// <summary>Game-over page carries the completed score.</summary>
internal static UiRoute<int> GameOver { get; } = new("game-over", new UiRouteOptions { Layer = 10, AllowBack = false, BlocksWorldActionInput = true });
/// <summary>Unsaved progress confirmation returns an explicit business choice.</summary>
internal static UiDialogRoute<Func<string>, bool> Confirm { get; } = new("confirm", Modal(40));
/// <summary>Content selection remains accessible even when the active package plan failed.</summary>
internal static UiRoute<bool> Content { get; } = new("content", Modal(30));
/// <summary>Content repair requires an explicit player decision before backup and downgrade.</summary>
internal static UiDialogRoute<Func<string>, bool> Recover { get; } = new("recover", Modal(40));
/// <summary>Executing an installed DLL requires a separate explicit authorization decision.</summary>
internal static UiDialogRoute<Func<string>, bool> CodePermission { get; } = new("code-permission", Modal(40));
/// <summary>Declares input and pause behavior independently of visual ordering.</summary>
private static UiRouteOptions Modal(int layer) => new()
{
Kind = UiRouteKind.Window,
Layer = layer,
Modal = true,
BlocksWorldActionInput = true,
BlocksWorldPointerInput = true,
PauseWhileVisible = true,
ContinueProcessingWhenPaused = true,
};
}Compose the services
Create a shared dispatcher, view root, and storage on the host thread. Register the page and window factories.
var root = new GodotUiRoot { Name = "Ui" };
AddChild(root);
var context = SynchronizationContext.Current ?? throw new InvalidOperationException("Godot synchronization context is unavailable.");
var dispatcher = new SynchronizationContextGameDispatcher(context);
_gameDispatcher = dispatcher;
_pause.RegisterHandler(new GodotPauseHandler(GetTree()));
_scenes = new SceneRouter(new WorldFactory(this), this, dispatcher);
var registry = new UiRegistry();
_menus = new DodgeMenus(this);
_menus.Register(registry);
_ui = new UiService(registry, root, dispatcher, _pause);
var input = new GodotUiInputBridge
{
Service = _ui,
RunAction = RunAction,
UnhandledCancelAsync = () => _world is { IsRunning: true }
? _ui.ShowAsync(DodgeRoutes.Pause, _world.Score, _lifetime.Token) : Task.CompletedTask,
};
AddChild(input);
_startup = StartAsync();Start a run
Call the application use case from the menu and show the corresponding UI.
/// <summary>Begins a fresh or restored run through the scene service.</summary>
internal async Task StartGameAsync(bool restore)
{
if (!CanStart)
throw new InvalidOperationException("Repair content selection and restart before playing.");
if (restore && _saveRetired)
throw new InvalidOperationException("This run has ended and cannot be continued.");
var saved = restore ? await LoadContentSaveAsync().ConfigureAwait(true) : null;
if (restore && saved is null)
return;
if (!restore)
_modState = _saves.CreateModState();
_arenaId = saved?.ArenaId ?? _content.ArenaId;
_world?.StopRun();
await _ui.ClearAsync(_lifetime.Token).ConfigureAwait(true);
await _scenes.ReplaceAsync("play", cancellationToken: _lifetime.Token).ConfigureAwait(true);
if (saved is null)
_world!.StartRun();
else
_world!.RestoreProgress(saved);
_dirty = true;
await _ui.ShowAsync(DodgeRoutes.Hud, _world!.Score, _lifetime.Token).ConfigureAwait(true);
}Pause and settings
Open the pause menu during play, then open Settings on top. Closing Settings leaves the main pause request active, and returning to the game resumes play. Keep settings preview separate from saving confirmed settings.
internal Task SaveSettingsAsync(DodgePreferences draft)
{
ArgumentNullException.ThrowIfNull(draft);
var captured = draft.Copy();
return UpdatePreferencesAsync(current =>
{
captured.BestScore = current.BestScore;
captured.Language = current.Language;
return captured;
});
}Save and continue
Capture and store a game snapshot. Restart, choose Continue, and check position and score. See implementing saves for the full flow.
/// <summary>Writes one explicit save slot, preserving the previous file on failure.</summary>
internal async Task SaveGameAsync()
{
if (_world is null)
return;
var saved = _world.CaptureProgress();
await _saves.SaveDocumentAsync(1, saved, _modState, _lifetime.Token).ConfigureAwait(true);
_saveRetired = false;
_savedPlayerPosition = new Vector2(saved.X, saved.Y);
_dirty = false;
_menus.SetStatus(() => Text.Get("run_saved"));
}Shut down the host
Wait for in-flight operations and native services to stop before releasing scene tree resources.
/// <summary>Stops UI admission, cancels waiting dialogs and joins accepted actions before freeing native roots.</summary>
internal async void RequestQuit()
{
if (_stopping)
return;
_stopping = true;
var exit = System.Environment.ExitCode;
var errors = new List<Exception>();
try
{
try
{
_lifetime.Cancel();
}
catch (Exception exception) { errors.Add(exception); }
_world?.StopRun();
await CaptureStopAsync(_ui.StopAsync, errors).ConfigureAwait(true);
await CaptureStopAsync(() => Task.WhenAll([.. _actions]), errors).ConfigureAwait(true);
await CaptureStopAsync(() => _startup, errors).ConfigureAwait(true);
await CaptureStopAsync(_scenes.StopAsync, errors).ConfigureAwait(true);
if (_content is not null)
await CaptureStopAsync(_content.StopModsAsync, errors).ConfigureAwait(true);
await CaptureStopAsync(() => _pause.DisposeAsync().AsTask(), errors).ConfigureAwait(true);
// QueueFree is frame-deferred. Let owned views leave the tree before disposing their shared theme.
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
// Native audio playback retires on the mixer thread, independently of fast headless process frames.
var audioDrain = Math.Clamp(AudioServer.GetTimeToNextMix() * 2, 0.12, 0.5);
await ToSignal(GetTree().CreateTimer(audioDrain, processAlways: true, processInPhysics: false, ignoreTimeScale: true), SceneTreeTimer.SignalName.Timeout);
}
catch (Exception exception) { errors.Add(exception); }
finally
{
DisposeOwnedResource(_menus, errors);
DisposeOwnedResource(_startupFont, errors);
DisposeOwnedResource(Text, errors);
DisposeOwnedResource(_content, errors);
DisposeOwnedResource(_storage, errors);
DisposeOwnedResource(_preferencesGate, errors);
DisposeOwnedResource(_lifetime, errors);
if (errors.Count > 0)
{
GD.PushError(new AggregateException("Game shutdown failed after cleanup.", errors).ToString());
exit = 1;
}
GetTree().Quit(exit);
}
}
/// <summary>Attempts every owned stop action even when an earlier callback reports an error.</summary>
private static async Task CaptureStopAsync(Func<Task> stop, List<Exception> errors)
{
try
{
await stop().ConfigureAwait(true);
}
catch (Exception exception) { errors.Add(exception); }
}
/// <summary>Releases one owned resource without skipping the remaining resources.</summary>
private static void DisposeOwnedResource(IDisposable? resource, List<Exception> errors)
{
try
{
resource?.Dispose();
}
catch (Exception exception) { errors.Add(exception); }
}Smoke test and export
godot --headless --path Samples/DodgeTheCreeps -- --smoke
godot --headless --path Samples/DodgeTheCreeps -- --persistence-smokeCheck for DODGE_SMOKE_RESULT PASS. Then use the ID printed by each flow with --smoke-continue=<id> or --persistence-smoke-continue=<id> to verify reading from a new process. Install matching .NET export templates and select Windows Desktop or Linux Desktop in Godot's Export panel.
Add DLC and mods
Use content packs to add records and assets, or implement a code mod contract. Preserve stable content IDs and verify that saved progress resolves the records it references.