Example Host
In this example a host node is used to handle game logic, physics, and network updates. It is the authority for the game state, and is responsible for broadcasting updates to the clients.
Prepare an events
object to handle events such as actorInput
.
Include the listenToClients
and broadcastClients
methods from the transport layer.
Echo-D Host Instance
Create a new Echo-D instance, and pass in the events
along with options.
The events
will be used to handle events such as actorInput
.
In this example we are using f32
for position
components, and compressing
strings as integers.
We are also setting isAuthority
to true
, and isSymbolLeader
to true
.
compressStringsAsInts
is enabled to reduce the size of messages.
The updateOptions
are used to specify which updates to send to the clients.
In this example we are only sending position
updates
and inputs
are masked from the host becayse they are only
allowed from clients.
Listen to Clients
Import the listenToClients
and broadcastClients
methods from the transport layer.
Listen to clients and handle incoming messages with Echo-D.
Game Loop
Use Echo-D to perform a game network update by broadcasting updates to the clients.
Create a game loop function to handle game logic, physics, and network updates.
Setup the game loop using setInterval
, or use a different
game loop method.
Actor Input Handler
Add an event listener for actorInput
events. This will be used to handle
actor inputs. In this example inputs are used to move the position
of actors.
Host Transport Layer
Choose a network transport layer such as
BroadcastChannel
, WebSocket
, or WebRTC
.
Create a BroadcastChannel
instance for broadcasting to game clients.
Now setup a message handler for the bcGameHost
.
This example only supports one host and multiple clients.
Handle messages by passing them to the Echo-D instance.
Implement a broadcastClients
method to broadcast a message to the clients.
Or use WebSocketServer
from a WebSocket
library such as ws
in a supported JavaScript environments such as Node.js.
msgpack
is also recommended for reducing the size of messages.
Especially when transporting over the network.
Keep a list of clients that will be used to broadcast updates.
Handle messages from clients by decoding them, and passing them to the Echo-D instance.
After a client disconnects, remove them from the list of clients.
Create a WebSocketServer
instance, and handle
websocket connections, add them to the list of clients,
and send an init message to the client.
When a message is received, pass it to the message handler.
Implement a broadcastClients
method to broadcast a message to
the WebSocket
clients.
Use msgpack
to encode the message before sending it.
Default Client Transport
Provide a way to import the broadcastClients
method from ./host/transport.js
.
Set the default transport to BroadcastChannel
.
Set the default transport to WebSocket
.