Sending Initial Game State in Match Join

When users join a match, I want the game state to be broadcasted to them so they can see where all the other players are.

We tried doing dispatcher.broadcast_message in the match_join event, but it seems like I can only broadcast to the existing users. The user currently joining I can’t send a message to ?

Is there a common pattern for client getting initial game state on joining match?

  1. Nakama version 3.10.0 on linux
  2. Lua Server Module
function M.match_join(context, dispatcher, tick, state, presences)
    for _, presence in ipairs(presences) do
        nk.logger_info(string.format("Presence %s named %s and state %s", presence.user_id, presence.username, nk.json_encode(presence)))
        state.presences[presence.session_id] = presence
        dummyinitialstate = {}
        dispatcher.broadcast_message(1, dummyinitialstate, nil, nil)
        -- or tried this also 
        dispatcher.broadcast_message(1, dummyinitialstate, { presence }, nil)
    return state

Hey @mattkanwisher, this is the correct approach, however the broadcast_message function expects the #2 argument to be a string, so you should use nk.json_encode on dummyinitialstate before passing it to the function.

Let me know if this helps.

It is a string, on Match_Join the problem is that it will NOT be broadcasted to the newly joined player so they don’t get initial state. We ended up having to have an initial state message, that all clients call. I think this is a shortcoming of the api

@mattkanwisher This code path has been tested extensively with live projects; it’s highly unlikely that this could be a bug in Nakama match runtime.

This could be that the client isn’t configured properly; I’d suggest the following on the client:

  1. Check that all network calls to Nakama are async/awaited - This means that you actually wait for the network request to complete between your logic runs further on the client.

  2. You connect the socket listeners before you attempt to make network request (or join a match). To me this sounds like the most probable issue as looks like you are missing some messages until the listener is connected.