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?
- Nakama version 3.10.0 on linux
- 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)
end
return state
end
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:
-
Check that all network calls to Nakama are async/await
ed - This means that you actually wait for the network request to complete between your logic runs further on the client.
-
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.