77 game-dev skills for AI coding agents — Godot, Unity, Unreal, Phaser, PixiJS, three.js, Bevy, pygame, LÖVE, Roblox. Portable SKILL.md Agent Skills (the format Anthropic launched as Claude Skills), with a router that loads the right skill for your engine and task. Runs in Claude Code, Cursor, Kiro, Codex, Copilot, Gemini CLI and more.
Python agent-skillsai-agentsantigravityawesome-listclaude-codeclinecodexcursorgame-devgame-developmentgamedevgemini-cligithub-copilotgodotkirooh-my-piskillsunityunrealwindsurf
feat(godot): add godot-multiplayer, godot-export, godot-csharp skills
AbhishekBarali17bab34e69138
diff --git a/skills/godot/godot-csharp/SKILL.md b/skills/godot/godot-csharp/SKILL.mdnew file mode 100644index 0000000..c05dbed--- /dev/null+++ b/skills/godot/godot-csharp/SKILL.md@@ -0,0 +1,175 @@+---+name: godot-csharp+description: >+ Use C#/.NET in Godot 4.x: partial classes extending nodes, the PascalCase lifecycle+ (_Ready/_Process/_PhysicsProcess), [Export] fields, [Signal] delegates as C# events,+ GetNode<T>, and calling between C# and GDScript. Use when writing Godot game code in+ C# (.cs files, .csproj), needing the Godot .NET build, converting GDScript patterns+ to C#, or wiring Godot signals as C# events.+license: Apache-2.0+compatibility: Godot 4.3+ .NET (C#, .NET 8 SDK)+metadata:+ engine: godot+ category: godot+ difficulty: intermediate+---++# Godot C# / .NET (4.x)++Write Godot game code in C#: node subclasses, the engine lifecycle, exports, signals as+events, and GDScript interop. Targets **Godot 4.3+ (.NET / C#)** with the **.NET 8 SDK**.++## When to use++- Use when scripting a Godot game in C# (`.cs` + `.csproj`), translating GDScript idioms+ to C#, exposing `[Export]` fields, or wiring `[Signal]` delegates and GetNode<T>.++**When *not* to use:** GDScript-specific syntax → `godot-gdscript`; engine concepts that+are language-neutral (scenes, physics, animation) → the relevant `godot-*` skill. You need+the **Godot .NET build** + the .NET SDK installed; the standard build can't run C#.++## Core workflow++1. **Use the Godot .NET editor build** and install the .NET 8 SDK. Creating the first C#+ script generates a `.csproj`/`.sln`. Build with the editor or `dotnet build`.+2. **Every node script is a `partial` class** extending a Godot type (the source generator+ relies on `partial`). The file/class name should match the node script.+3. **Override lifecycle methods in PascalCase** with `double` delta: `_Ready()`,+ `_Process(double delta)`, `_PhysicsProcess(double delta)`.+4. **Expose tunables with `[Export]`**; they show in the Inspector like GDScript `@export`.+5. **Declare signals as `[Signal]` delegates** named `XxxEventHandler`; emit with+ `EmitSignal(SignalName.Xxx, ...)` and subscribe with the generated C# `event`.+6. **Get nodes with `GetNode<T>("Path")`** (or `%Unique`), and call into GDScript with+ `Call`/`Get`/`Set` when needed.++## Patterns++### 1. A node script: lifecycle, [Export], GetNode<T>++```csharp+using Godot;++public partial class Player : CharacterBody2D+{+ [Export] public float Speed = 200.0f; // editable in the Inspector+ [Export] public float JumpVelocity = -400.0f;++ private const float Gravity = 1200.0f;+ private AnimatedSprite2D _sprite;++ public override void _Ready()+ {+ _sprite = GetNode<AnimatedSprite2D>("AnimatedSprite2D");+ }++ public override void _PhysicsProcess(double delta)+ {+ Vector2 v = Velocity; // Velocity is a property here+ if (!IsOnFloor())+ v.Y += Gravity * (float)delta; // delta is double; cast for float math+ if (Input.IsActionJustPressed("jump") && IsOnFloor())+ v.Y = JumpVelocity;++ float dir = Input.GetAxis("move_left", "move_right");+ v.X = dir != 0 ? dir * Speed : Mathf.MoveToward(v.X, 0, Speed);++ Velocity = v;+ MoveAndSlide(); // no args, like GDScript 4.x+ }+}+```++### 2. Signals as C# events++```csharp+using Godot;++public partial class Health : Node+{+ // Delegate name MUST end with "EventHandler"; generator creates the event + SignalName.+ [Signal] public delegate void HealthChangedEventHandler(int current, int max);++ private int _hp = 100;++ public void TakeDamage(int amount)+ {+ _hp = Mathf.Max(_hp - amount, 0);+ EmitSignal(SignalName.HealthChanged, _hp, 100); // type-safe signal name+ }++ public override void _Ready()+ {+ HealthChanged += OnHealthChanged; // subscribe like a normal C# event+ }++ private void OnHealthChanged(int current, int max) => GD.Print($"HP {current}/{max}");+}+```++### 3. Instancing a scene in C#++```csharp+public partial class Spawner : Node2D+{+ // Load once; PackedScene is the C# equivalent of preload's result.+ private readonly PackedScene _bullet = GD.Load<PackedScene>("res://bullet.tscn");++ public void Shoot(Vector2 at)+ {+ var b = _bullet.Instantiate<Node2D>(); // typed instantiate+ b.GlobalPosition = at;+ AddChild(b);+ }+}+```++### 4. Interop with GDScript nodes++```csharp+public override void _Ready()+{+ Node gd = GetNode("GDScriptNode");+ // Call a GDScript method and read/write its properties dynamically.+ gd.Call("take_damage", 10);+ int score = (int)gd.Get("score");+ gd.Set("score", score + 5);+ // Connect to a GDScript signal by name:+ gd.Connect("died", Callable.From(OnDied));+}++private void OnDied() => GD.Print("entity died");+```++## Pitfalls++- **Forgetting `partial`.** Without `partial`, the Godot source generator can't extend the+ class and `[Export]`/`[Signal]` break with confusing build errors.+- **Wrong method case/signature.** C# overrides are `_Ready`, `_Process(double)`,+ `_PhysicsProcess(double)` — PascalCase and `double` delta (GDScript uses snake_case and+ `float`). A mismatched name just won't be called.+- **`[Signal]` delegate naming.** It must end with `EventHandler`; the engine exposes the+ signal as the name without that suffix and generates `SignalName.X` and a C# `event`.+- **`GD.Print` vs `Console.WriteLine`.** Use `GD.Print`/`GD.PrintErr` to reach the Godot+ output panel; `Console` output may not appear.+- **Value-type structs.** `Vector2`, `Color`, `Transform2D` are structs — mutate a local+ copy (`var v = Velocity; v.X = ...; Velocity = v;`); editing `Velocity.X` directly won't+ compile/persist.+- **Needs the .NET build + SDK.** The non-.NET editor can't run C#; mismatched/missing+ .NET SDK causes build failures. Match the SDK to the Godot version (4.3 → .NET 8).+- **`QueueFree()` vs `Free()`** — same rules as GDScript; prefer `QueueFree()`. Disposed+ objects throw `ObjectDisposedException` if used after freeing.+- **Export to some platforms differs for .NET** (e.g. extra steps for web/mobile); check+ the .NET export notes for your target.++## References++- For export attribute variants (`[ExportGroup]`, ranges, typed arrays), async with+ `await ToSignal(...)`, `Godot.Collections` vs System collections, custom Resources in+ C#, and project/build setup, read `references/csharp-setup-and-interop.md`.++## Related skills++- `godot-gdscript` — the GDScript equivalents of these patterns.+- `godot-signals-groups` — signal/event architecture (language-neutral).+- `godot-resources` — data resources; the C# `[Export]` + `Resource` pattern.+- `unity-csharp-scripting` — C# in Unity, for developers coming from there.diff --git a/skills/godot/godot-csharp/references/csharp-setup-and-interop.md b/skills/godot/godot-csharp/references/csharp-setup-and-interop.mdnew file mode 100644index 0000000..cc1d7c4--- /dev/null+++ b/skills/godot/godot-csharp/references/csharp-setup-and-interop.md@@ -0,0 +1,107 @@+# Godot C# setup & interop reference (Godot 4.3+ .NET)++Depth companion to `godot-csharp`.++## Project setup++- Use the **Godot .NET** editor build (labeled ".NET"/"Mono").+- Install the matching **.NET SDK** (Godot 4.3 targets **.NET 8**).+- The first C# script creates `<Project>.csproj` and `<Project>.sln`. The `.csproj` sets+ `<TargetFramework>net8.0</TargetFramework>` and references `GodotSharp`.+- Build via the editor (it builds on play) or `dotnet build`. Editor Settings let you pick+ an external editor (VS, VS Code, Rider).+- Add NuGet packages by editing the `.csproj` `<ItemGroup>` and rebuilding.++## Export attributes++```csharp+[Export] public int Lives = 3;+[Export(PropertyHint.Range, "0,100,1")] public int Percent;+[Export(PropertyHint.Range, "0,1,0.01,or_greater")] public float Gain = 1f;+[Export(PropertyHint.File, "*.json")] public string DataPath;+[Export(PropertyHint.Enum, "Idle,Walk,Run")] public string State;+[Export] public Godot.Collections.Array<PackedScene> Waves = new();+[Export] public NodePath TargetPath;++[ExportGroup("Movement")]+[Export] public float Speed = 200f;+[ExportSubgroup("Air")]+[Export] public float AirControl = 0.4f;++[ExportCategory("Debug")]+[Export] public bool ShowGizmos;+```++`[ExportGroup]`/`[ExportSubgroup]`/`[ExportCategory]` organize the Inspector.++## Collections: Godot vs System++- `Godot.Collections.Array` and `Godot.Collections.Dictionary` (and generic+ `Array<T>`/`Dictionary<TKey,TValue>`) are Variant-backed and can be `[Export]`ed, passed+ to engine APIs, and shared with GDScript.+- `System.Collections.Generic.List<T>`/`Dictionary<,>` are normal C#; faster for pure C#+ logic but **cannot** be exported or passed directly to engine calls expecting Variants.+- Convert as needed: `new Godot.Collections.Array<int>(myList)`.++## Async with signals++```csharp+public async void OpenChest()+{+ var anim = GetNode<AnimationPlayer>("AnimationPlayer");+ anim.Play("open");+ await ToSignal(anim, AnimationPlayer.SignalName.AnimationFinished);+ SpawnLoot();+}++// Timer await:+await ToSignal(GetTree().CreateTimer(0.5), SceneTreeTimer.SignalName.Timeout);+```++`ToSignal(obj, SignalName.X)` is the C# equivalent of GDScript `await obj.x`.++## Custom Resource in C#++```csharp+using Godot;++[GlobalClass] // makes it appear in the New Resource dialog+public partial class ItemResource : Resource+{+ [Export] public string DisplayName { get; set; } = "Item";+ [Export] public int Value { get; set; }+ [Export] public Texture2D Icon { get; set; }+}+```++`[GlobalClass]` is the C# analog of GDScript `class_name`. Load/duplicate as usual:+`GD.Load<ItemResource>("res://sword.tres")`, `resource.Duplicate(true)`.++## Calling C# from GDScript++A C# `[GlobalClass]` or any C# node is usable from GDScript by its node/class. GDScript+calls C# methods/properties directly when the C# member is `public`. Conversely C# calls+GDScript via `Call`/`Get`/`Set` and connects with `Callable.From(method)` or+`new Callable(this, MethodName.OnFoo)`.++## Common Godot C# API equivalents++| GDScript | C# |+|----------|-----|+| `print(x)` | `GD.Print(x)` |+| `preload`/`load` | `GD.Load<T>("res://...")` |+| `instantiate()` | `packed.Instantiate<T>()` |+| `$Path` / `get_node` | `GetNode<T>("Path")` |+| `%Unique` | `GetNode<T>("%Unique")` |+| `queue_free()` | `QueueFree()` |+| `emit_signal("x", a)` | `EmitSignal(SignalName.X, a)` |+| `randf()` / `randi()` | `GD.Randf()` / `GD.Randi()` |+| `deg_to_rad(d)` | `Mathf.DegToRad(d)` |+| `is_instance_valid(o)` | `GodotObject.IsInstanceValid(o)` |++## Build/export notes++- Release exports compile C# ahead-of-time per target. Some platforms (web, mobile) have+ extra .NET export requirements/steps — check the current .NET export docs for your+ target before shipping.+- Keep generated `obj/`, `bin/`, and `.godot/` out of version control (`.gitignore`).diff --git a/skills/godot/godot-export/SKILL.md b/skills/godot/godot-export/SKILL.mdnew file mode 100644index 0000000..0abb2aa--- /dev/null+++ b/skills/godot/godot-export/SKILL.md@@ -0,0 +1,129 @@+---+name: godot-export+description: >+ Export and build a Godot 4.x project for distribution: install export templates,+ define export presets (Windows/macOS/Linux/Web/Android), run headless command-line+ exports for CI, and handle web (HTML5) COOP/COEP and dedicated-server/headless+ builds. Use when exporting a Godot game, configuring export_presets.cfg, building+ for web/desktop/mobile, or automating builds from the command line.+license: Apache-2.0+compatibility: Godot 4.3++metadata:+ engine: godot+ category: godot+ difficulty: intermediate+---++# Godot Export & Builds (4.x)++Turn a project into runnable platform builds via export presets and the command line, and+handle the web/dedicated-server gotchas. Targets **Godot 4.3+**.++## When to use++- Use when producing a shippable build: installing export templates, creating/editing+ export presets, exporting from the editor or headless CLI (CI), or troubleshooting web+ (HTML5) and dedicated-server exports.++**When *not* to use:** storefront publishing flows → `steam-publish`/`itch-publish`; the+networking code of a server → `godot-multiplayer` (this skill covers building it headless).++## Core workflow++1. **Install export templates** matching your engine version: Editor menu >+ *Manage Export Templates* (download), or install the `.tpz` offline. Versions must+ match the editor exactly.+2. **Add export presets** in *Project > Export*: pick a platform (Windows Desktop, macOS,+ Linux, Web, Android, iOS), set the export path, icons, features, and resource+ include/exclude filters. Presets are saved to `export_presets.cfg`.+3. **Export from the editor** with *Export Project* (release) or *Export PCK/ZIP*.+4. **Or export headless from the CLI** for automation/CI using+ `--export-release "<preset name>" <output path>`.+5. **Per platform:** Web needs cross-origin isolation (COOP/COEP) for threads; Android+ needs the SDK/keystore; macOS/iOS need signing for distribution.+6. **Smoke-test the build** on the target before shipping — exported builds use `res://`+ read-only; write to `user://`.++## Patterns++### 1. Headless CLI export (CI-friendly)++```bash+# Preset name must match exactly what's in Project > Export (quote it).+# Run from the project directory (where project.godot lives).+godot --headless --export-release "Windows Desktop" build/windows/game.exe+godot --headless --export-release "Linux/X11" build/linux/game.x86_64+godot --headless --export-release "Web" build/web/index.html++# Debug build (includes debug symbols / remote debug):+godot --headless --export-debug "Windows Desktop" build/windows/game_debug.exe++# Export only the data pack (no executable):+godot --headless --export-pack "Linux/X11" build/game.pck+```++### 2. Run a project headless (dedicated server / tests)++```bash+# No window/GPU — for a server build or automated runs.+godot --headless --path . res://server_main.tscn+# Quit automatically after N seconds for a smoke test:+godot --headless --path . --quit-after 600+```++### 3. Detect the build context at runtime++```gdscript+func _ready() -> void:+ if OS.has_feature("dedicated_server") or DisplayServer.get_name() == "headless":+ _start_server_only() # skip rendering/UI on a headless server+ if OS.has_feature("web"):+ _apply_web_tweaks()+ # Custom feature tags (added per preset) are also queryable:+ # if OS.has_feature("demo"): limit_content()+```++### 4. Choose write paths that survive export++```gdscript+# res:// is READ-ONLY in exported games. Always write to user://.+func save_path() -> String:+ return "user://savegame.tres" # resolves to the OS app-data dir++func _ready() -> void:+ print(OS.get_user_data_dir()) # where user:// actually lives+```++## Pitfalls++- **"No export template found".** Templates must match the exact editor version (incl.+ beta/rc). Re-download via *Manage Export Templates* after upgrading Godot.+- **Preset name mismatch in CLI.** `--export-release "Windows"` fails if the preset is+ named `"Windows Desktop"`. Names are case- and space-sensitive; quote them.+- **Web build shows a blank page / threads error.** HTML5 builds that use threads require+ the server to send `Cross-Origin-Opener-Policy: same-origin` and+ `Cross-Origin-Embedder-Policy: require-corp` (cross-origin isolation for+ `SharedArrayBuffer`). Must be served over HTTP(S), not opened as a `file://`. itch.io has+ a "SharedArrayBuffer support" toggle for this.+- **Writing to `res://` at runtime fails** in exports (read-only, packed). Use `user://`.+- **Missing resources in the build.** Non-resource files (e.g. external `.json`, `.txt`)+ are not auto-included — add them via the preset's *Resources > Filters to export+ non-resource files* (e.g. `*.json`).+- **Android export needs setup**: Android SDK/JDK paths in Editor Settings, a debug or+ release **keystore**, and the `INTERNET` permission for networked games.+- **macOS/iOS distribution requires signing/notarization**; unsigned macOS apps are+ blocked by Gatekeeper.+- **Debug vs release.** `--export-debug` enables remote debugging and debug checks; ship+ `--export-release`.++## References++- For the `export_presets.cfg` structure, all useful CLI flags, custom feature tags,+ PCK/expansion patching, encryption, and per-platform setup (Android keystore, macOS+ signing, web headers), read `references/presets-and-cli.md`.++## Related skills++- `godot-multiplayer` — the dedicated-server code you export headless.+- `steam-publish` / `itch-publish` — getting the build to players.+- `prototype-fast` / `game-jam` — quick web/desktop builds for sharing.diff --git a/skills/godot/godot-export/references/presets-and-cli.md b/skills/godot/godot-export/references/presets-and-cli.mdnew file mode 100644index 0000000..886d028--- /dev/null+++ b/skills/godot/godot-export/references/presets-and-cli.md@@ -0,0 +1,98 @@+# Export presets & CLI reference (Godot 4.3+)++Depth companion to `godot-export`.++## export_presets.cfg++Generated/edited by *Project > Export*; commit it so CI and teammates share presets. It is+an INI-style file with a `[preset.N]` block per preset and a matching `[preset.N.options]`+block. Example shape (do not hand-author from scratch — let the editor create it):++```ini+[preset.0]+name="Windows Desktop"+platform="Windows Desktop"+runnable=true+export_path="build/windows/game.exe"+custom_features=""+exclude_filter=""+include_filter=""++[preset.0.options]+binary_format/embed_pck=false+application/icon="res://icon.ico"+application/product_name="My Game"+codesign/enable=false+```++Sensitive values (keystore passwords, encryption keys) live in `export_presets.cfg` too —+keep them out of public repos or inject them in CI rather than committing.++## Useful command-line flags++```+godot --headless run without a window/GPU+ --path <dir> project directory (where project.godot is)+ --export-release "<preset>" <out> export a release build+ --export-debug "<preset>" <out> export a debug build+ --export-pack "<preset>" <out> export only the .pck/.zip data+ --quit-after <frames|seconds> auto-quit (smoke tests)+ --main-pack <file.pck> run a specific data pack+ --verbose detailed logging+ -- <args> pass args to your game (OS.get_cmdline_user_args())+```++Use the exact preset `name` (case/space-sensitive). Run from the project dir or pass+`--path`. Exit code is non-zero on export failure — check it in CI.++## Custom feature tags++Add tags under a preset's *Features* (or `custom_features`) and branch at runtime with+`OS.has_feature("tag")`. Common built-ins: `web`, `windows`, `macos`, `linux`, `android`,+`ios`, `mobile`, `pc`, `debug`, `release`, `editor`, `template`, `dedicated_server`,+`64`/`32`. Use a `demo` tag to ship a content-limited build from the same project.++## Web (HTML5) specifics++- Output is `index.html` + `.js`/`.wasm`/`.pck`. Serve over HTTP(S).+- Threaded builds need **cross-origin isolation**:+ - `Cross-Origin-Opener-Policy: same-origin`+ - `Cross-Origin-Embedder-Policy: require-corp`+ Without these, `SharedArrayBuffer` is unavailable and the engine errors or falls back.+- itch.io: enable "This file will be played in the browser" and the SharedArrayBuffer+ support option. GitHub Pages can't set the headers — use a host that can, or a service+ worker shim.+- Reduce size: enable compression, trim unused features, and consider the+ "Extensions Support" toggle only if needed.++## Android++- Set Android SDK + OpenJDK paths in Editor Settings > Export > Android.+- Install the Android build template (Project > Install Android Build Template) for custom+ Gradle builds / plugins.+- Provide a **debug keystore** (auto for debug) and a **release keystore** for store+ builds. Add the `INTERNET` permission for networked games.+- Choose architectures (arm64-v8a is standard for modern devices).++## macOS / iOS++- macOS distribution: enable codesign, provide an Apple Developer ID, and notarize the+ `.app`/`.dmg`; otherwise Gatekeeper blocks it.+- iOS: exports an Xcode project; build/sign/submit through Xcode.++## PCK patching & DLC++Export extra content as a separate `.pck` and load it at runtime:++```gdscript+var ok := ProjectSettings.load_resource_pack("user://dlc1.pck") # mounts into res://+```++A patch pack can override or add files. Use `--export-pack` to produce packs in CI.++## Encryption++Set a 64-hex-char script encryption key (Project > Export, or `GODOT_SCRIPT_ENCRYPTION_KEY`+env for CLI) and enable "Encrypt Exported PCK". Note: client-side encryption deters casual+inspection but cannot fully protect assets on a user's machine — don't store true secrets+in the build.diff --git a/skills/godot/godot-multiplayer/SKILL.md b/skills/godot/godot-multiplayer/SKILL.mdnew file mode 100644index 0000000..0fe3db9--- /dev/null+++ b/skills/godot/godot-multiplayer/SKILL.md@@ -0,0 +1,157 @@+---+name: godot-multiplayer+description: >+ Build networked games with Godot 4.x high-level multiplayer: set up an+ ENetMultiplayerPeer server/client, define RPCs with the @rpc annotation+ (call via rpc()/rpc_id()), set per-node multiplayer authority, and replicate+ state with MultiplayerSpawner and MultiplayerSynchronizer. Use when adding+ multiplayer/networking to a Godot project, writing @rpc functions, or syncing+ player/world state across peers.+license: Apache-2.0+compatibility: Godot 4.3+ (high-level multiplayer, ENet)+metadata:+ engine: godot+ category: godot+ difficulty: advanced+---++# Godot Multiplayer (4.x high-level)++Connect peers, call functions remotely with `@rpc`, assign authority, and replicate state+with `MultiplayerSpawner`/`MultiplayerSynchronizer`. Targets **Godot 4.3+** (ENet). Treat+all client input as untrusted; keep the server authoritative.++## When to use++- Use when adding networked multiplayer: hosting/joining over ENet, calling RPCs,+ assigning per-node authority, or auto-spawning/syncing nodes across peers.++**When *not* to use:** local split-screen (no networking); raw TCP/UDP/WebSocket protocol+work (low-level `PacketPeer`); HTTP requests. For save/persistence → `save-systems`.++## Core workflow++1. **Create a peer** (`ENetMultiplayerPeer`), call `create_server(port, max)` or+ `create_client(ip, port)`, and assign it to `multiplayer.multiplayer_peer`. The+ server's unique ID is always `1`; clients get random positive IDs.+2. **Handle connection signals** on `multiplayer`: `peer_connected(id)`,+ `peer_disconnected(id)`, `connected_to_server`, `connection_failed`,+ `server_disconnected`.+3. **Define RPCs** with `@rpc(...)`. Call them on a `Callable` via `rpc()` (all peers) or+ `rpc_id(peer_id)` (one peer). Inside, `multiplayer.get_remote_sender_id()` tells you who+ sent it.+4. **Keep RPC signatures identical** on every peer that runs the script — Godot checksums+ all `@rpc` methods in a script; mismatches break silently.+5. **Assign authority** per node with `set_multiplayer_authority(id)`; gate input/RPCs by+ `is_multiplayer_authority()`.+6. **Replicate state** with `MultiplayerSpawner` (auto-instances scenes on clients) and+ `MultiplayerSynchronizer` (auto-syncs selected properties).+7. **Validate on the server.** Don't trust client-reported positions/results.++## Patterns++### 1. Host or join (ENet)++```gdscript+const PORT := 7000+const MAX_PLAYERS := 8++func host() -> void:+ var peer := ENetMultiplayerPeer.new()+ var err := peer.create_server(PORT, MAX_PLAYERS)+ if err != OK:+ push_error("Cannot host: %s" % err); return+ multiplayer.multiplayer_peer = peer+ multiplayer.peer_connected.connect(_on_peer_connected)++func join(ip := "127.0.0.1") -> void:+ var peer := ENetMultiplayerPeer.new()+ peer.create_client(ip, PORT)+ multiplayer.multiplayer_peer = peer+ multiplayer.connected_to_server.connect(func(): print("connected"))++func leave() -> void:+ multiplayer.multiplayer_peer = OfflineMultiplayerPeer.new()+```++### 2. RPCs: client sends input to the server (any_peer, call_local)++```gdscript+func _unhandled_input(event: InputEvent) -> void:+ if event.is_action_pressed("fire") and is_multiplayer_authority():+ request_fire.rpc_id(1) # send only to the server (id 1)++# Clients may call this; it runs on the server (and locally if server is a player).+@rpc("any_peer", "call_local", "reliable")+func request_fire() -> void:+ var sender := multiplayer.get_remote_sender_id()+ if not _can_fire(sender): # server-side validation+ return+ spawn_projectile.rpc(sender) # tell everyone to spawn it++@rpc("authority", "call_local", "reliable")+func spawn_projectile(owner_id: int) -> void:+ _do_spawn(owner_id)+```++### 3. Per-node authority (each player controls their own avatar)++```gdscript+extends CharacterBody2D++func _ready() -> void:+ # The node name is the owning peer's id; that peer is the authority.+ set_multiplayer_authority(name.to_int())++func _physics_process(delta: float) -> void:+ if not is_multiplayer_authority():+ return # only the owner reads input & moves+ velocity = Input.get_vector("left", "right", "up", "down") * 200.0+ move_and_slide()+```++### 4. MultiplayerSynchronizer config (editor + replication)++```gdscript+# Add a MultiplayerSynchronizer child; in its Replication editor add the properties to+# sync (e.g. position, velocity). Set "Sync"/"Spawn" flags per property. From code you+# can scope visibility:+@onready var sync: MultiplayerSynchronizer = $MultiplayerSynchronizer++func _ready() -> void:+ # Only replicate this node to a specific peer (e.g. private info).+ sync.set_visibility_for(target_peer_id, true)+```++## Pitfalls++- **RPC signature checksum.** Every `@rpc` method in a script must exist with the same+ declaration on both client and server builds — *even unused ones*. A mismatch causes+ errors that may point at the wrong function. Argument names/count are not checked, but+ the set of RPCs and their annotations are.+- **Default `@rpc` is `"authority"`.** Clients calling it are ignored unless you set+ `"any_peer"`. Use `"call_local"` so the host (also a player) runs it too.+- **NodePaths must match across peers.** RPC routing uses the node's path/name; spawn nodes+ with identical names on all peers (use `MultiplayerSpawner` or `add_child(node, true)` for+ readable, deterministic names).+- **Trusting the client.** Never let clients set authoritative state (health, position,+ hits) directly. Send *intent*, validate on the server, then broadcast results.+- **RPC on non-Node classes fails.** `@rpc` methods must be on `Node`-derived classes, not+ plain `Resource`/`RefCounted`.+- **RPCs don't serialize Objects/Callables.** Pass plain data (ints, strings, arrays,+ dictionaries, PackedArrays).+- **Forgetting to reset the peer.** To disconnect cleanly, set+ `multiplayer.multiplayer_peer = OfflineMultiplayerPeer.new()`.+- **Android needs INTERNET permission** in the export preset or all networking is blocked.++## References++- For `MultiplayerSpawner` setup, transfer modes/channels, `SceneMultiplayer`+ authentication (`auth_callback`/`complete_auth`), a lobby skeleton, and dedicated-server+ export notes, read `references/replication-and-rpc.md`.++## Related skills++- `godot-nodes-scenes` — instancing the scenes that get spawned/synced.+- `godot-signals-groups` — connection signals and event flow.+- `godot-export` — exporting a headless dedicated server build.diff --git a/skills/godot/godot-multiplayer/references/replication-and-rpc.md b/skills/godot/godot-multiplayer/references/replication-and-rpc.mdnew file mode 100644index 0000000..492ab9d--- /dev/null+++ b/skills/godot/godot-multiplayer/references/replication-and-rpc.md@@ -0,0 +1,113 @@+# Replication & RPC reference (Godot 4.3+)++Depth companion to `godot-multiplayer`.++## The @rpc annotation in full++```gdscript+@rpc(mode, sync, transfer_mode, transfer_channel)+```++Defaults — `@rpc` is equivalent to `@rpc("authority", "call_remote", "reliable", 0)`:++- **mode**: `"authority"` (only the node's multiplayer authority may call remotely) or+ `"any_peer"` (any client may call — needed for player input).+- **sync**: `"call_remote"` (does not run on the local/sending peer) or `"call_local"`+ (also runs locally — use when the host is a player).+- **transfer_mode**: `"reliable"` (acknowledged, ordered, slower), `"unreliable"`+ (fire-and-forget, may drop/reorder — good for frequent position updates), or+ `"unreliable_ordered"` (drops late packets to preserve order).+- **transfer_channel**: integer channel index; the first three args can be in any order+ but the channel must be last. Use separate channels to keep unrelated streams from+ blocking each other.++Call forms (on a `Callable` for the method):++```gdscript+my_method.rpc(args...) # call on all peers (per mode/sync rules)+my_method.rpc_id(peer_id, args) # call on one peer (1 = server)+multiplayer.get_remote_sender_id() # inside the method: who invoked it+```++## MultiplayerSpawner++Auto-instantiates scenes on remote peers when the authority spawns them.++1. Add a `MultiplayerSpawner` node; set its **Spawn Path** to the parent that will hold+ spawned instances.+2. Add the scenes it may spawn to its **Auto Spawn List** (or use a custom spawn function+ via `spawn_function`).+3. On the authority, call `spawner.spawn(data)` or simply `add_child()` a scene under the+ spawn path — the spawner replicates it to clients with a matching name.++```gdscript+@onready var spawner: MultiplayerSpawner = $MultiplayerSpawner++func server_spawn_player(id: int) -> void:+ var p := preload("res://player.tscn").instantiate()+ p.name = str(id) # deterministic name = authority id+ $Players.add_child(p, true) # true = readable, replicated name+```++## MultiplayerSynchronizer++Replicates chosen properties from the authority to other peers each network tick.++- Add it as a child of the node to sync. In the **Replication** dock, add property paths+ (e.g. `:position`, `:velocity`, `Sprite2D:modulate`).+- Per property: **Spawn** (sent once at spawn) and **Sync** (sent continuously) flags, plus+ a replication interval.+- `replication_interval` / `delta_interval` tune bandwidth.+- Visibility filtering for per-peer data:+ ```gdscript+ sync.set_visibility_for(peer_id, true)+ sync.add_visibility_filter(func(peer): return _can_see(peer))+ sync.update_visibility()+ ```++Only the authority's values are sent; remote peers receive read-only updates. Combine with+per-node authority so each player's synchronizer pushes that player's state.++## SceneMultiplayer authentication++Protect RPCs from unauthenticated peers using the built-in handshake:++```gdscript+# Server, after assigning the peer:+multiplayer.auth_timeout = 3.0+multiplayer.auth_callback = func(peer_id: int, data: PackedByteArray):+ var info := JSON.parse_string(data.get_string_from_utf8())+ if _valid(info):+ multiplayer.complete_auth(peer_id)++# Client:+multiplayer.peer_authenticating.connect(func(peer_id: int):+ var payload := JSON.stringify({"token": _token}).to_utf8_buffer()+ multiplayer.send_auth(1, payload)+)+```++`connected_to_server` / `peer_connected` only fire once both sides call `complete_auth()`.++## Transfer mode guidance++- **Player input / commands** → reliable (must not be lost).+- **Position/rotation updates** → unreliable or unreliable_ordered via a+ `MultiplayerSynchronizer` (frequent, latest-wins).+- **Chat / state changes** → reliable, possibly on a dedicated channel.++## Dedicated server export++Export a **headless** build (no GPU) for servers; see `godot-export`. Modify the lobby so+the server is not counted as a player and the first joining client can start the match. Run+with the server feature tag and `--headless`.++## Minimal lobby flow++1. Host: `create_server`; add self to `players` keyed by id 1.+2. On `peer_connected(id)`: send your player info to that id via `rpc_id`.+3. Each peer registers others (`@rpc("any_peer")` register function using+ `get_remote_sender_id()`).+4. On `peer_disconnected(id)`: erase from `players`, emit a UI signal.+5. Server starts the game by RPC'ing a `load_game(path)` (`@rpc("call_local","reliable")`)+ so all peers `change_scene_to_file` together.