Player-to-player (p2p) messages are a useful mechanism when creating more advanced games. A p2p message is essentially a "packet" with an ID and a few arguments.
You can send p2p messages by calling gms_p2p_send
. It requires a player_id to whom the message will be sent, an id, and optionally up to 14 arguments. You can choose the ID to be anything between 0 and 255. It's useful to make macros for these IDs, so that you can easily see what an ID is supposed to do. In my examples, I always add macros prefixed with p2p_.
To receive p2ps you'll need to set a script using gms_script_set_p2p
. That script will be called whenever the game receives a p2p message from another player. The general structure of that script should look something like this:
var mid = argument0, sender = argument1, args = argument2;
show_error("Unknown p2p message with message id " + string(mid) + " received!", true)
The piece of code between the case [id]: and the break statement is the code that will be executed when a p2p message with that id is received. I'll annotate future code with just '// p2p_...' to keep it readable. It should be inside the p2p script, inside the switch-statement.
Keeping kill count
So you want to keep track of how many kills everyone makes. You'll need a way to let the killer know that he killed someone. You can do this by sending a p2p message whenever a player dies to its killer. For example:
// obj_player, event: collision with synced bullet
gms_p2p_send(p2p_got_kill, other.owner) // other.owner is automatically set by the extension
// p2p_got_kill, inside p2p script:
show_message("I killed " + string(gms_other_get(sender, 'name')) + "!")
score += 1 // Or whatever else you want to do
Special sending targets
Since update 18.104.22.168 GameMaker Server supports sending P2P messages to more than one player at a time. The following special values can be used instead of a player_id:
- gms_p2p_all_in_room - sends the message to all players in the same room as you
- gms_p2p_all_in_session - sends the message to all players in the same session
- gms_p2p_all_in_game - sends the message to all players in your game that are running the same game version, which you set in gms_settings
Note in particular 'gms_p2p_all_in_game', which can now be used to communicate across different sessions. One use case for this might be broadcasting global admin messages.