Mugon.start and the context
The entry point of every game and everything the context offers.
Loading the SDK
With a bundler:
// The SDK must be imported first: importing it says hello to the platform.
import { Mugon } from "@mugon/sdk";
Mugon.start(async (ctx) => {
console.log(`running as ${ctx.role} with id ${ctx.ownId}`);
});Without a bundler (Unity, Godot, Rust/wasm shells, plain JS) use the self-contained
mugon.iife.js from the package (node_modules/@mugon/sdk/dist/mugon.iife.js) as the first
script of your index.html:
<script src="./mugon.iife.js"></script>
<script type="module" src="./main.js"></script>It defines a global Mugon with Mugon.start and Mugon.Channel.
If the platform doesn't hear from your game within 20 seconds it shows "The game did not respond". The usual cause is a game that doesn't load the SDK, or loads it too late.
Mugon.start(callback)
Mugon.start waits for the platform's context, runs callback(ctx) and returns a promise that
settles when the callback does. Call it once. Outside a mugon iframe it rejects.
When the callback's promise resolves, the platform treats the game as loaded and closes its
loading overlay. If your game keeps running inside the callback, call
ctx.progress.done() yourself, see loading progress.
The context
ctx is frozen and only exists inside the callback. The SDK also publishes it as
window.mugon before the callback runs, for code that can't be handed it (a wasm module, see
Bevy).
| Member | Meaning |
|---|---|
role | "server" (the host) or "client". |
ownId | This peer's id. |
serverId | The server peer's id. Equals ownId on the server. |
initialPeers | Peers connected when the game started. Later joins and leaves arrive as connect and disconnect events. A client's initialPeers always contains the server. |
settings | Game settings from the platform. Currently always empty. |
send(peerId, data, channel?) | Send a Uint8Array to a peer. |
drop(peerId) | Disconnect a peer. |
on(event, handler) | Subscribe to "connect", "disconnect" and "message". Returns an unsubscribe function. |
showInvite() | Ask the platform to show the join QR code. |
toggleFullscreen() | Toggle fullscreen (call it from a click handler). |
progress.set(fraction, label?) | Report loading progress. |
progress.done() | Say the game is playable. |
Events
ctx.on("connect", (peerId) => { /* a peer joined */ });
ctx.on("disconnect", (peerId) => { /* a peer left */ });
ctx.on("message", ({ from, channel, data }) => { /* data is a Uint8Array */ });Events that arrive before you subscribe are queued and delivered to your first handler, so a game that loads for a while doesn't lose messages.
Sending
import { Channel } from "@mugon/sdk";
ctx.send(peerId, new Uint8Array([1, 2, 3]), Channel.UnreliableUnordered);Channel is one of ReliableOrdered (the default), ReliableUnordered, UnreliableOrdered
and UnreliableUnordered. send transfers the buffer of the array you pass, which detaches
it. Pass a copy if you still need the data.