制作 Godot 小游戏
这个示例把移动、刷怪、碰撞和计分接入 GFramework 的类型化 UI、暂停与存档。先运行完整工程,再按下面的顺序查看接线。
准备工具
安装仓库 SDK 和匹配的 Godot .NET 编辑器。下列命令均从仓库根目录执行。
构建与启动
bash
dotnet build Samples/DodgeTheCreeps/DodgeTheCreeps.csproj -c Debug
godot --headless --editor --path Samples/DodgeTheCreeps --import
godot --path Samples/DodgeTheCreeps素材
查看素材与授权。复用素材时保留对应许可与署名。
玩家移动
用原生角色接收方向输入并驱动动画。
csharp
/// <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);
}敌人、碰撞与计分
从玩法循环更新敌人与分数,游戏结束时结束当前局的存档。
csharp
/// <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);
}csharp
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;
}
}
}页面和窗口
用强类型路由定义 HUD、设置与退出确认的参数和策略。
csharp
// 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,
};
}装配服务
在宿主线程上创建共享调度器、视图根和存储,注册页与窗口的工厂。
csharp
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();开始游戏
从菜单调用用例启动一局,并切换到对应 UI。让菜单把用户动作交给应用入口。
csharp
/// <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);
}暂停与设置
运行游戏后打开暂停页,再叠加设置窗口。关闭设置后,暂停页继续持有暂停请求;返回游戏后才恢复玩法。将设置的预览和确认写入拆开。
csharp
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;
});
}保存与继续
捕获独立的游戏快照并保存。重新运行后选择继续,检查位置和分数。实现细节见实现存档。
csharp
/// <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"));
}宿主关闭
等待正在进行的工作和原生服务完成退出,再释放场景树资源。
csharp
/// <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); }
}自检与导出
bash
godot --headless --path Samples/DodgeTheCreeps -- --smoke
godot --headless --path Samples/DodgeTheCreeps -- --persistence-smoke检查 DODGE_SMOKE_RESULT PASS。然后使用对应流程输出的标识运行 --smoke-continue=<id> 或 --persistence-smoke-continue=<id>,验证新进程读取行为。安装匹配的 .NET 导出模板后,从 Godot Export 面板选择 Windows Desktop 或 Linux Desktop。
加入 DLC 与模组
运行内容包流程为游戏添加定义和资源,或实现代码模组契约。保留内容包的稳定 ID,验证已保存的游戏数据能找到对应记录。
下一步:把纯 C# 用例移出 Godot 宿主。