Question

I'm working on a small multiplayer 2D XNA Game using TCP. My issue is that when more than 2 people connect everyone starts to lag out. Currently for every new x,y position the player has it sends it as a packet to the server to broadacast to every other player connected on the network. This ultimately sends a massive amount of packets which I think causes the issue I'm having.

Is it normal to send every x,y coordinate to every player or am I doing something wrong?

Was it helpful?

Solution

Instead of sending every packet, you should only send packets when the player changes direction, by either jumping, or moving left/right. The clients should handle gravity and collision as normal, while the server validates it.

When they move, send a packet containing:

  1. Their movement vector (This should be a small Vector2 or Point that is either -1, 0, or 1 on each axis. -1 X means they are moving left, 0 means no movement, and 1 means right movement)

    You should implement this client side already if you have not (Don't just add X to the velocity when you move, assign it to a movement variable to use later.

    Ex:

    if (KeyState.IsKeyDown(Keys.Left) { Movement.X = -1 } ... Velocity += Movement * Speed

  2. Their current position. Send the players current position (The serverside and validated one) to all other players, to make sure their position matches (It may be off due to small changes)

  3. Their current velocity. The velocity of the player should have changed when the movement changed, since they are now going a different direction. Send the velocity along with the position.

Overall, only when a player moves (Ex: Stops holding the left key or presses the jump key) and NOT every frame, send the movement (Direction you are going based on keyboard input), position, and velocity.

Once you have this completed, you may want to add interpolation, which will smooth the movements between updates and make it look less jerky.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top