using DarkRift; using DarkRift.Client; using DarkRift.Client.Unity; using System.Collections.Generic; using UnityEngine; using System; /// /// Handles the synchronization of other player's characters. /// internal class BlockCharacterManager : MonoBehaviour { /// /// The unit client we communicate via. /// [SerializeField] [Tooltip("The client to communicate with the server via.")] UnityClient client; /// /// The characters we are managing. /// Dictionary characters = new Dictionary(); void Awake() { if (client == null) { Debug.LogError("No client assigned to BlockPlayerSpawner component!"); return; } client.MessageReceived += Client_MessageReceived; } /// /// Called when a message is received from the server. /// /// /// void Client_MessageReceived(object sender, MessageReceivedEventArgs e) { using (Message message = e.GetMessage() as Message) { //Check the tag if (message.Tag == BlockTags.Movement) { using (DarkRiftReader reader = message.GetReader()) { //Read message Vector3 newPosition = new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()); Vector3 newRotation = new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()); ushort id = reader.ReadUInt16(); //Update characters to move to new positions characters[id].NewPosition = newPosition; characters[id].NewRotation = newRotation; } } } } /// /// Adds a character to the list of those we're managing. /// /// The ID of the owning player. /// The character to synchronize. public void AddCharacter(ushort id, BlockNetworkCharacter character) { characters.Add(id, character); } /// /// Removes a character from the list of those we're managing. /// /// The ID of the owning player. public void RemoveCharacter(ushort id) { Destroy(characters[id].gameObject); characters.Remove(id); } /// /// Removes all characters that are being managded. /// internal void RemoveAllCharacters() { foreach (BlockNetworkCharacter character in characters.Values) Destroy(character.gameObject); characters.Clear(); } }