I’m working on a multiplayer horde game and I’ve gotten players to connect and sync properly, but I’m having trouble with syncing up enemy NPCs because of how p2p events send data.
My current approach is to have one player have the “real” enemies on their client, and then simultaneously send all the enemy x,y positions data to the other clients and update positions. But since triggering events on all clients can only send a scene variable, I’m not entirely sure how to send every NPC object’s x,y position variables simultaneously.
I think a scene array could do this, where every enemy that spawns receives an ID, is added into the array, and then continuously update their x,y position, but I don’t know how to structure and update them how I want.
That’s the host-client pattern The “host” client handles most of the game logic, and the clients are being shown the current state of the game held by the host.
To be able to have multiple enemies, you can do something like this: Whenever the host creates a new enemy, you’ll want to generate a new UID (Unique IDentifier) for that entity. You can do it easily with the UUID extension. Ask all the instances to create that object and use an object variable to remember which ID belongs to this instance:
Then, you can use a for each object to read all of the enemy’s data individually on the host, and a for each variable event to apply all the data on the client. Use the variable condition and object picking to target the instance you want:
The network is something extremely slow and unreliable compared to a computer, and are often limited. If you send 60 events per second, a lot of data will be sent, and if the network can’t keep up, the sending of the new data might be throttled until it finishes sending the older data, causing increasing amounts of delay and desynchronization.
It usually isn’t much of a problem to send less data per second, games like TF2 or Minecraft only send an update 20 times per second. My example is a bit less, only 5 times a second, but I didn’t really test it out, you can change it to 0.05s to mirror the behavior of those games. The reduced amount of data uses tween (interpolation) to generate the missing values.
This is not only good for bot overloading the network but also because it makes updates independent of frame rate: a host on a lower frame rate wouldn’t send enough updates to the others, a host on a higher frame rate would send more than the clients need or can handle. We can now also know how much time there is between each update, which is helpful, since we can just tween a bit longer than the average update to deal with spike lags (as the tween behavior will generate new positions for a few more milliseconds).