Search Unity

Multiplayer problem in unity websockets

Discussion in 'Multiplayer' started by tushar_unity775, Aug 3, 2022.

  1. tushar_unity775

    tushar_unity775

    Joined:
    Jun 17, 2022
    Posts:
    20
    hello everyone

    i am facing an error in unity 3d and websockets .

    problem :
    1. the player is respawning every time after 2 seconds
    2. Player animations are not updating in unity



    this is my client side code ..


    Code (JavaScript):
    1. const WebSocket = require('ws')
    2.  
    3. // create new websocket server
    4. const wss = new WebSocket.Server({port: 8000})
    5.  
    6. // empty object to store all players
    7. var players = {}
    8.  
    9. // add general WebSocket error handler
    10. wss.on('error', function error (error) {
    11.   console.error('WebSocket error', error)
    12. })
    13.  
    14. // on new client connect
    15. wss.on('connection', function connection (client) {
    16.   console.log('new client connected')
    17.   // on new message recieved
    18.   client.on('message', function incoming (data) {
    19.     // get data from string
    20.     var [udid, x, y, z] = data.toString().split('\t')
    21.     // store data to players object
    22.     players[udid] = {
    23.       position: {
    24.         x: parseFloat(x),
    25.         y: parseFloat(y) + 1,
    26.         z: parseFloat(z)
    27.       },
    28.       timestamp: Date.now()
    29.     }
    30.     // save player udid to the client
    31.     client.udid = udid
    32.   })
    33. })
    34.  
    35. function broadcastUpdate () {
    36.   broadcast messages to all clients
    37.   wss.clients.forEach(function each (client) {
    38.     // filter disconnected clients
    39.     if (client.readyState !== WebSocket.OPEN) return
    40.     // filter out current player by client.udid
    41.     var otherPlayers = Object.keys(players).filter(udid => udid !== client.udid)
    42.     // create array from the rest
    43.     var otherPlayersPositions = otherPlayers.map(udid => players[udid])
    44.     // send it
    45.     client.send(JSON.stringify({players: otherPlayersPositions}))
    46.   })
    47.  
    48. }
    49.  
    50. // call broadcastUpdate every 0.1s
    51. setInterval(broadcastUpdate, 20000)
    52.  
    53.  

    and this is my server side code


    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using System;
    4. using System.Collections.Generic;
    5.  
    6. // define classed needed to deserialize recieved data
    7. [Serializable]
    8. public class Position {
    9.     public Vector3 position;
    10.     public int timestamp;
    11. }
    12. [Serializable]
    13. public class Players {
    14.    public List<Position> players;
    15. }
    16.  
    17. public class Multiplayer : MonoBehaviour {
    18.  
    19.   // define public game object used to visualize other players
    20.   public GameObject otherPlayerObject;
    21.  
    22.   private Vector3 prevPosition;
    23.   private List<GameObject> otherPlayers = new List<GameObject>();
    24.  
    25.   IEnumerator Start () {
    26.     // get player
    27.     GameObject player = GameObject.Find("FPSController");
    28.  
    29.     // connect to server
    30.     WebSocket w = new WebSocket(new Uri("ws://localhost:8000"));
    31.     yield return StartCoroutine(w.Connect());
    32.     Debug.Log("CONNECTED TO WEBSOCKETS");
    33.  
    34.     // generate random ID to have idea for each client (feels unsecure)
    35.     System.Guid myGUID = System.Guid.NewGuid();
    36.  
    37.     // wait for messages
    38.     while (true) {
    39.       // read message
    40.       string message = w.RecvString();
    41.       // check if message is not empty
    42.       if (message != null) {
    43.         // Debug.Log("RECEIVED FROM WEBSOCKETS: " + reply);
    44.  
    45.         // deserialize recieved data
    46.         Players data = JsonUtility.FromJson<Players>(message);
    47.  
    48.         // if number of players is not enough, create new ones
    49.         if (data.players.Count > otherPlayers.Count) {
    50.           for (int i = 0; i < data.players.Count - otherPlayers.Count; i++) {
    51.             otherPlayers.Add(Instantiate(otherPlayerObject, data.players[otherPlayers.Count + i].position, Quaternion.identity));
    52.           }
    53.         }
    54.  
    55.         // update players positions
    56.         for (int i = 0; i < otherPlayers.Count; i++) {
    57.           // using animation
    58.           otherPlayers[i].transform.position = Vector3.Lerp(otherPlayers[i].transform.position, data.players[i].position, Time.deltaTime * 10F);
    59.           // or without animation
    60.           // otherPlayers[i].transform.position = data.players[i].position;
    61.         }
    62.       }
    63.  
    64.       // if connection error, break the loop
    65.       if (w.error != null) {
    66.         Debug.LogError("Error: " + w.error);
    67.         break;
    68.       }
    69.  
    70.       // check if player moved
    71.       if (prevPosition != player.transform.position) {
    72.         // send update if position had changed
    73.         w.SendString(myGUID + "\t" + player.transform.position.x + "\t" + player.transform.position.y + "\t" + player.transform.position.z);
    74.         prevPosition = player.transform.position;
    75.       }
    76.  
    77.       yield return 0;
    78.     }
    79.  
    80.     // if error, close connection
    81.     w.Close();
    82.   }
    83. }
    84.  

    please help me with this issue ..
     
  2. tushar_unity775

    tushar_unity775

    Joined:
    Jun 17, 2022
    Posts:
    20
    sorry the above one is server side and the 2nd one is client side