Synchronization between Server and Client
In RPGJS, synchronization between the server and the client is a crucial aspect to ensure a consistent and immersive gameplay experience. This readme will guide you through the process of synchronizing data between the server and the client, utilizing schemas and hooks provided by RPGJS.Understanding RPGJS Schemas and Data Synchronization
RPGJS uses schemas to define the structure of data that needs to be synchronized between the server and the client. These schemas ensure that the properties of entities, such as players and items, are consistent and correctly communicated between the server and the client. Properties are implemented as signals, which provide reactivity - when a property changes using the.set() method, it is automatically sent to the client, keeping the game state up-to-date.
Schemas work within the context of a “room” in RPGJS, where a room is essentially a map in the game world. It’s important to note that when a player changes maps, synchronization can be lost if not handled properly.
Best Practices for Synchronization
Avoid Synchronization Issues After Changing Maps**
When a player changes maps, it’s crucial not to continue executing the code in theonConnected method immediately. This is because the properties might not be synchronized with the client yet. Instead, use the onJoinMap hook to ensure synchronization before performing any actions.
Custom Synchronization with Schemas**
You can also create custom synchronization by extending existing schemas or defining new ones. Example:wood to the player entity and ensured its synchronization with the client. The use of signals (.set() method) enables reactivity, which is essential for automatic synchronization. Any changes you make to this property will be automatically sent to the client, maintaining a consistent game state for all players.
Retrieving Synchronization on Client Side
Once you have set up synchronization on the server side, you need to retrieve and use this synchronized data on the client side.Custom WebSocket Events
Besides synchronized signals, you can also exchange custom websocket events between the server and the client.Receive server events on the client
Inject the websocket service withWebSocketToken, then subscribe with on().
player.emit() for one player or map.broadcast() for the whole map.
Send client events to the server
Emit custom websocket events from the client with the same injected socket.player.on() for one player or map.on() to listen at map level.
Using the onInit Hook for Sprites
TheonInit hook is called when a sprite instance is created, but before the component is displayed. This is the perfect place to access synchronized properties and set up reactive data.