Search Unity

Not able to update player rotation over UNET.

Discussion in 'UNet' started by BeastBurst, Jun 22, 2017.

  1. BeastBurst

    BeastBurst

    Joined:
    Dec 18, 2016
    Posts:
    15
    I'm using unity 5.5.

    Here is my code.

    Client.cs:
    Code (CSharp):
    1.  
    2. public class Player
    3. using System.Collections;
    4. using System.Collections.Generic;
    5. using System.Text;
    6. using UnityEngine;
    7. using UnityEngine.Networking;
    8. using UnityEngine.UI;
    9.  
    10. {
    11.    public string playerName;
    12.    public GameObject avatar;
    13.    public int connectionId;
    14. }
    15.  
    16.  
    17. public class Client : MonoBehaviour
    18. {
    19.  
    20.    private const int MAX_CONNECTION = 100;
    21.  
    22.    private string ServerIp = "127.0.0.1";
    23.  
    24.    private int port = 5701;
    25.    private int hostId;
    26.  
    27.    private int ourClientId;
    28.  
    29.    private int reliableChannel;
    30.    private int unreliableChannel;
    31.  
    32.    private int connectionId;
    33.  
    34.    private float connectionTime;
    35.    private bool isStarted = false;
    36.    private bool isConnected = false;
    37.  
    38.    private string PlayerName;
    39.  
    40.  
    41.    public GameObject characterPrefab;
    42.    public Dictionary<int,Player> Players = new Dictionary<int, Player>();
    43.  
    44.    private byte error;
    45.  
    46.    public void Connect()
    47.    {
    48.        // Does the player have a name ?
    49.  
    50.        string pName = GameObject.Find("NameInput").GetComponent<InputField>().text;
    51.  
    52.        if(PlayerName == "")
    53.        {
    54.            Debug.Log("You must write you name!");
    55.            return;
    56.        }
    57.  
    58.        PlayerName = pName;
    59.  
    60.        NetworkTransport.Init();
    61.  
    62.        ConnectionConfig cc = new ConnectionConfig();
    63.  
    64.        reliableChannel = cc.AddChannel(QosType.Reliable);
    65.        unreliableChannel = cc.AddChannel(QosType.Unreliable);
    66.  
    67.        HostTopology topo = new HostTopology(cc, MAX_CONNECTION);
    68.  
    69.        hostId = NetworkTransport.AddHost(topo, 0);
    70.        connectionId = NetworkTransport.Connect(hostId,ServerIp,port,0, out error);
    71.  
    72.        connectionTime = Time.time;
    73.        isConnected = true;
    74.    }
    75.  
    76.    private void Update()
    77.    {
    78.        if (!isConnected)
    79.        {
    80.            return;
    81.        }
    82.  
    83.        int recHostId;
    84.        int connectionId;
    85.        int channelId;
    86.        byte[] recBuffer = new byte[1024];
    87.        int bufferSize = 1024;
    88.        int dataSize;
    89.        byte error;
    90.        NetworkEventType recData = NetworkTransport.Receive(out recHostId, out connectionId, out channelId, recBuffer, bufferSize, out dataSize, out error);
    91.        switch (recData)
    92.        {
    93.  
    94.            case NetworkEventType.DataEvent:       //3
    95.                string msg = Encoding.Unicode.GetString(recBuffer, 0, dataSize);
    96.                Debug.Log("Receiving: " + msg);
    97.  
    98.                string[] splitData = msg.Split('|');
    99.  
    100.                switch (splitData[0])
    101.                {
    102.                    case "ASKPLAYERNAME":
    103.                        OnAskName(splitData);
    104.                    break;
    105.  
    106.                    case "CNN":
    107.                        SpawnPlayer(splitData[1],int.Parse(splitData[2]));
    108.                        break;
    109.                    case "DC":
    110.                        CharacterDisconnected(int.Parse(splitData[1]));
    111.                        break;
    112.                    case "ASKCHARACTERPOSITION":
    113.                        OnAskPosition(splitData);
    114.                        break;
    115.                    default:
    116.                        Debug.Log("Invalid Client meesage : " + msg);
    117.                        break;
    118.  
    119.                }
    120.  
    121.                break;
    122.  
    123.        }
    124.    }
    125.  
    126.    private void OnAskName(string[] data)
    127.    {
    128.        ourClientId = int.Parse(data[1]);
    129.  
    130.        //Send our name to the server.
    131.  
    132.        Send("PLAYERNAME|" + PlayerName, reliableChannel);
    133.  
    134.        //Create all the other players.
    135.  
    136.        for(int i = 2; i < data.Length - 1; i++)
    137.        {
    138.            string[] d = data[I].Split('%');
    139.  
    140.                SpawnPlayer(d[0], int.Parse(d[1]));
    141.  
    142.        }
    143.    }
    144.  
    145.    private void OnAskPosition(string[] data)
    146.    {
    147.        if (!isStarted)
    148.            return;
    149.        //Update everyone else position;
    150.        for (int i = 1; i <= data.Length - 1; i++)
    151.        {
    152.            string[] d = data[I].Split('%');
    153.            //Prevent the server from updating us.
    154.            if (ourClientId != int.Parse(d[0]))
    155.            {
    156.                Vector3 position = Vector3.zero;
    157.                Quaternion rotation = Quaternion.Euler(float.Parse(d[4]), float.Parse(d[5]), float.Parse(d[6]));
    158.                position.x = float.Parse(d[1]);
    159.                position.y = float.Parse(d[2]);
    160.                position.z = float.Parse(d[3]);
    161.                Players[int.Parse(d[0])].avatar.transform.position = position;
    162.                //Debug.Log("My position" + transform.position + "- Going to:" + position);
    163.                Players[int.Parse(d[0])].avatar.transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * 10);
    164.            }
    165.  
    166.  
    167.        }
    168.        //Send our own position;
    169.        Vector3 myPosition = Players[ourClientId].avatar.transform.position; //Taking my position.
    170.        Quaternion myRotation = Players[ourClientId].avatar.transform.rotation; //Taking my rotaion.
    171.        Debug.Log("Character rotation:" + myRotation);
    172.        string m = "CHARACTERPOSITION|" + myPosition.x.ToString() + '|' + myPosition.y.ToString() + '|' + myPosition.z.ToString() + '|' + myRotation.x.ToString() + '|' + myRotation.y.ToString() + '|' + myRotation.z.ToString();
    173.        Send(m, unreliableChannel);
    174.  
    175.  
    176.    }
    177.  
    178.    private void SpawnPlayer(string playerName, int cnnid)
    179.    {
    180.        GameObject go = Instantiate(characterPrefab) as GameObject;
    181.  
    182.        // Is this ours?
    183.        if(cnnid == ourClientId)
    184.        {
    185.            // Add mobility.
    186.            go.AddComponent<CharacterMovement>();
    187.            go.AddComponent<Character>();
    188.            // REmove canvas.
    189.            GameObject.Find("Canvas").SetActive(false);
    190.            isStarted = true;
    191.        }
    192.  
    193.        Player p = new Player();
    194.        p.avatar = go;
    195.        p.playerName = playerName;
    196.        p.connectionId = cnnid;
    197.        p.avatar.GetComponentInChildren<TextMesh>().text = playerName;
    198.        Players.Add(cnnid,p);
    199.  
    200.    }
    201.  
    202.    private void CharacterDisconnected(int cnnid)
    203.    {
    204.        Destroy(Players[cnnid].avatar);
    205.        Players.Remove(cnnid);
    206.    }
    207.  
    208.    private void Send(string message, int channelId)
    209.    {
    210.        Debug.Log("Sending : " + message);
    211.        byte[] msg = Encoding.Unicode.GetBytes(message);
    212.             NetworkTransport.Send(hostId, connectionId, channelId, msg, message.Length * sizeof(char), out error);
    213.  
    214.    }
    215. }
    216.  
    Here is my Server.cs:
    Code (CSharp):
    1.  
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using System.Text;
    5. using UnityEngine;
    6. using UnityEngine.Networking;
    7.  
    8. public class ServerClient
    9. {
    10.    public int connectionId;
    11.    public string playerName;
    12.    public Vector3 playerPosition;
    13.    public Quaternion playerRotation;
    14. }
    15.  
    16. public class Server : MonoBehaviour
    17. {
    18.    private const int MAX_CONNECTION = 100;
    19.  
    20.    private int port = 5701;
    21.    private int hostId;
    22.  
    23.    private int reliableChannel;
    24.    private int unreliableChannel;
    25.  
    26.    private bool isStarted = false;
    27.    private byte error;
    28.  
    29.    private List<ServerClient> clients = new List<ServerClient>();
    30.  
    31.    private float lastMovementUpdate;
    32.    private float movementUpdateRate = 0.05f;
    33.  
    34.    private void Start()
    35.    {
    36.        NetworkTransport.Init();
    37.  
    38.        ConnectionConfig cc = new ConnectionConfig();
    39.  
    40.        reliableChannel = cc.AddChannel(QosType.Reliable);
    41.        unreliableChannel = cc.AddChannel(QosType.Unreliable);
    42.  
    43.        HostTopology topo = new HostTopology(cc, MAX_CONNECTION);
    44.  
    45.        hostId = NetworkTransport.AddHost(topo, port, null);
    46.  
    47.        isStarted = true;
    48.    }
    49.  
    50.    private void Update()
    51.    {
    52.        if (!isStarted)
    53.        {
    54.            return;
    55.        }
    56.  
    57.        int recHostId;
    58.        int connectionId;
    59.        int channelId;
    60.        byte[] recBuffer = new byte[1024];
    61.        int bufferSize = 1024;
    62.        int dataSize;
    63.        byte error;
    64.        NetworkEventType recData = NetworkTransport.Receive(out recHostId, out connectionId, out channelId, recBuffer, bufferSize, out dataSize, out error);
    65.        switch (recData)
    66.        {
    67.            case NetworkEventType.ConnectEvent:    //2
    68.                Debug.Log("Player " + connectionId + " has connected.");
    69.                OnConnection(connectionId);
    70.                break;
    71.            case NetworkEventType.DataEvent:       //3
    72.                string msg = Encoding.Unicode.GetString(recBuffer, 0, dataSize);
    73.                Debug.Log("Receiving from " + connectionId + " has sent : " + msg);
    74.                string[] splitData = msg.Split('|');
    75.  
    76.                switch (splitData[0])
    77.                {
    78.                    case "PLAYERNAME":
    79.                        OnPlayerName(connectionId, splitData[1]);
    80.                        break;
    81.                    case "CHARACTERPOSITION":
    82.                        OnCharacterPosition(connectionId, float.Parse(splitData[1]), float.Parse(splitData[2]), float.Parse(splitData[3]), float.Parse(splitData[4]), float.Parse(splitData[5]), float.Parse(splitData[6]));
    83.                        break;
    84.                    default:
    85.                        Debug.Log("Invalid Server meesage : " + msg);
    86.                        break;
    87.  
    88.                }
    89.  
    90.                break;
    91.  
    92.                break;
    93.            case NetworkEventType.DisconnectEvent: //4
    94.                Debug.Log("Player " + connectionId + " has disconnected.");
    95.                OnDisconnection(connectionId);
    96.                break;
    97.        }
    98.  
    99.        //Ask player for position.
    100.        if(Time.time - lastMovementUpdate > movementUpdateRate)
    101.        {
    102.            lastMovementUpdate = Time.time;
    103.            string m = "ASKCHARACTERPOSITION|";
    104.  
    105.            foreach (ServerClient sc in clients)
    106.            {
    107.                m += sc.connectionId.ToString() + '%' + sc.playerPosition.x.ToString() + '%' + sc.playerPosition.y.ToString() + '%' + sc.playerPosition.z.ToString() + '%' + sc.playerRotation.x.ToString() + '%' + sc.playerRotation.y.ToString() + '%' + sc.playerRotation.z.ToString() + '|';
    108.            }
    109.            m = m.Trim('|');
    110.            Send(m, unreliableChannel, clients);
    111.        }
    112.    }
    113.    private void OnConnection(int cnnId)
    114.    {
    115.        // Add him to online list
    116.        ServerClient c = new ServerClient();
    117.        c.connectionId = cnnId;
    118.        c.playerName = "TEMP";
    119.        clients.Add(c);
    120.  
    121.  
    122.        // Assing player id
    123.  
    124.        // Request player name and send to all players
    125.  
    126.        string msg = "ASKPLAYERNAME|" + cnnId + "|";
    127.        foreach (ServerClient sc in clients)
    128.        {
    129.            msg += sc.playerName + '%' + sc.connectionId + '|';
    130.        }
    131.            msg = msg.Trim('|');
    132.            Send(msg, reliableChannel, cnnId);
    133.  
    134.  
    135.    }
    136.    private void OnDisconnection(int cnnId)
    137.    {
    138.        // Remove player from our client list
    139.        clients.Remove(clients.Find(x => x.connectionId == cnnId));
    140.        //Tell everyone somebody dissconnected
    141.        Send("DC|" + cnnId, reliableChannel, clients);
    142.    }
    143.    private void OnPlayerName(int cnnId, string playerName)
    144.    {
    145.        // Ling the name to the connection id.
    146.        clients.Find(x => x.connectionId == cnnId).playerName = playerName;
    147.        // Tell everybody new player has connected.
    148.        Send("CNN|" + playerName + '|' + cnnId, reliableChannel, clients);
    149.    }
    150.    private void OnCharacterPosition(int cnnId, float x, float y, float z, float rx, float ry, float rz)
    151.    {
    152.        Quaternion characterRotation = Quaternion.Euler(rx,ry,rz);
    153.        Debug.Log("Character rotation: " + characterRotation);
    154.        clients.Find(c => c.connectionId == cnnId).playerPosition = new Vector3(x, y, z);
    155.        //clients.Find(c => c.connectionId == cnnId).playerRotation = Quaternion.Euler(new Vector3(0, 30, 0));
    156.    }
    157.    private void Send(string message, int channelId, int cnnId)
    158.        {
    159.            List<ServerClient> c = new List<ServerClient>();
    160.            c.Add(clients.Find(x => x.connectionId == cnnId));
    161.            Send(message, channelId, c);
    162.        }
    163.    private void Send(string message, int channelId, List<ServerClient> c)
    164.        {
    165.            Debug.Log("Sending : " + message);
    166.            byte[] msg = Encoding.Unicode.GetBytes(message);
    167.            foreach(ServerClient sc in c)
    168.            {
    169.                NetworkTransport.Send(hostId, sc.connectionId, channelId, msg, message.Length * sizeof(char), out error);
    170.            }
    171.        }
    172.  
    173.    }
    174.  
    Here is my CharacterMovement.cs:
    Code (CSharp):
    1.  
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5.  
    6. public class CharacterMovement : MonoBehaviour
    7. {
    8.    private CharacterController controller;
    9.    private float verticalVelocity;
    10.  
    11.    private void Start()
    12.    {
    13.        controller = GetComponent<CharacterController>();
    14.  
    15.  
    16.    }
    17.  
    18.    private void Update()
    19.    {
    20.        //inputs = location variable
    21.        Vector3 location = Vector3.zero;
    22.  
    23.        location.x = Input.GetAxis("Horizontal");
    24.  
    25.        if (controller.isGrounded)
    26.        {
    27.            verticalVelocity = -1;
    28.            if (Input.GetButton("Jump"))
    29.            {
    30.                verticalVelocity = 10;
    31.            }
    32.  
    33.            if (Input.GetKey(KeyCode.W))
    34.            {
    35.                transform.position += transform.forward * Time.deltaTime * CharacterGlobals.CharacterMovementSpeed;
    36.                Debug.Log("Location: " + transform.position);
    37.                //Debug.Log("Character speed is: " + CharacterGlobals.CharacterMovementSpeed);
    38.            }
    39.  
    40.            if (Input.GetKey(KeyCode.S))
    41.            {
    42.                transform.position -= transform.forward * Time.deltaTime * CharacterGlobals.CharacterMovementSpeed;
    43.                // Decrease character speed by - CharacterGlobals.CharacterMovementSpeed -= 1;
    44.                Debug.Log("Location: " + transform.position);
    45.            }
    46.  
    47.            if (Input.GetKey(KeyCode.A))
    48.            {
    49.                transform.Rotate(0, -3, 0);
    50.            }
    51.  
    52.            if (Input.GetKey(KeyCode.D))
    53.            {
    54.                transform.Rotate(0, 3, 0);
    55.            }
    56.        }
    57.        else
    58.        {
    59.            verticalVelocity -= 14.0f * Time.deltaTime;
    60.        }
    61.  
    62.        location.y = verticalVelocity;
    63.  
    64.        controller.Move(location * Time.deltaTime);
    65.    }
    66. }
    67.  
    I have created a successfully multyplayer connection. When character login it is spawned and when it moves the position is synced well. So i am able to update character position but i'm not able to update character rotation. I binded rotation of the character on pressing buttons A and D. There is no problem on the character 1 to rotate but you can not see that rotation on character 2.

    I hope i have explained my problem well enough. Where i my mistake? Why the character position does not update?