/// <summary> /// Creates a new <see cref="ExampleNetworkedEntity"/> with the given <see cref="ColyseusNetworkedEntityView"/> and attributes /// and places it at the provided position and rotation. /// </summary> /// <param name="room">The room the entity will be added to</param> /// <param name="position">Position for the new entity</param> /// <param name="rotation">Position for the new entity</param> /// <param name="attributes">Position for the new entity</param> /// <param name="viewToAssign">The provided view that will be assigned to the new <see cref="ExampleNetworkedEntity"/></param> /// <param name="callback">Callback that will be invoked with the newly created <see cref="ExampleNetworkedEntity"/></param> public void CreateNetworkedEntityWithTransform(ColyseusRoom <ExampleRoomState> room, Vector3 position, Quaternion rotation, Dictionary <string, object> attributes = null, ColyseusNetworkedEntityView viewToAssign = null, Action <ExampleNetworkedEntity> callback = null) { if (attributes != null) { attributes.Add("creationPos", new object[3] { position.x, position.y, position.z }); attributes.Add("creationRot", new object[4] { rotation.x, rotation.y, rotation.z, rotation.w }); } else { attributes = new Dictionary <string, object>() { ["creationPos"] = new object[3] { position.x, position.y, position.z }, ["creationRot"] = new object[4] { rotation.x, rotation.y, rotation.z, rotation.w } }; } CreateNetworkedEntity(room, attributes, viewToAssign, callback); }
/// <summary> /// Creates a new <see cref="ExampleNetworkedEntity"/> with the given prefab and attributes /// and places it at the provided position and rotation. /// </summary> /// <param name="room">The room the entity will be added to</param> /// <param name="prefab">Prefab you would like to use to create the entity</param> /// <param name="position">Position for the new entity</param> /// <param name="rotation">Position for the new entity</param> /// <param name="attributes">Position for the new entity</param> public void InstantiateNetworkedEntity(ColyseusRoom <ExampleRoomState> room, string prefab, Vector3 position, Quaternion rotation, Dictionary <string, object> attributes = null) { if (string.IsNullOrEmpty(prefab)) { LSLog.LogError("No Prefab Declared"); return; } if (attributes != null) { attributes.Add("creationPos", new object[3] { position.x, position.y, position.z }); attributes.Add("creationRot", new object[4] { rotation.x, rotation.y, rotation.z, rotation.w }); } else { attributes = new Dictionary <string, object>() { ["creationPos"] = new object[3] { position.x, position.y, position.z }, ["creationRot"] = new object[4] { rotation.x, rotation.y, rotation.z, rotation.w } }; } CreateNetworkedEntity(room, prefab, attributes); }
/// <summary> /// Join a room with the given <see cref="roomId" />. /// </summary> /// <param name="roomId">ID of the room to join.</param> public async Task JoinRoomId(string roomId) { LSLog.Log($"Joining Room ID {roomId}...."); ClearRoomHandlers(); try { while (_room == null || !_room.colyseusConnection.IsOpen) { _room = await _client.JoinById <ExampleRoomState>(roomId); if (_room == null || !_room.colyseusConnection.IsOpen) { LSLog.LogImportant($"Failed to Connect to {roomId}.. Retrying in 5 Seconds..."); await Task.Delay(5000); } } LSLog.LogImportant($"Connected to {roomId}.."); _lastRoomId = roomId; RegisterRoomHandlers(); } catch (Exception ex) { LSLog.LogError(ex.Message); LSLog.LogError("Failed to join room"); //await CreateSpecificRoom(_client, roomName, roomId, onJoin); } }
/// <summary> /// Sends "ping" message to current room to help measure latency to the server. /// </summary> /// <param name="roomToPing">The <see cref="ColyseusRoom{T}" /> to ping.</param> private void RunPingThread(object roomToPing) { ColyseusRoom <ExampleRoomState> currentRoom = (ColyseusRoom <ExampleRoomState>)roomToPing; const float pingInterval = 0.5f; // seconds const float pingTimeout = 15f; //seconds int timeoutMilliseconds = Mathf.FloorToInt(pingTimeout * 1000); int intervalMilliseconds = Mathf.FloorToInt(pingInterval * 1000); DateTime pingStart; while (currentRoom != null) { _waitForPong = true; pingStart = DateTime.Now; _lastPing = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); _ = currentRoom.Send("ping"); while (currentRoom != null && _waitForPong && DateTime.Now.Subtract(pingStart).TotalSeconds < timeoutMilliseconds) { Thread.Sleep(200); } if (_waitForPong) { LSLog.LogError("Ping Timed out"); } Thread.Sleep(intervalMilliseconds); } }
/// <summary> /// Create a room with the given roomId. /// </summary> /// <param name="roomId">The ID for the room.</param> public async Task CreateSpecificRoom(ColyseusClient client, string roomName, string roomId) { LSLog.LogImportant($"Creating Room {roomId}"); try { //Populate an options dictionary with custom options provided elsewhere as well as the critical option we need here, roomId Dictionary <string, object> options = new Dictionary <string, object> { ["roomId"] = roomId }; foreach (KeyValuePair <string, object> option in roomOptionsDictionary) { options.Add(option.Key, option.Value); } _room = await client.Create <ExampleRoomState>(roomName, options); } catch (Exception ex) { LSLog.LogError($"Failed to create room {roomId} : {ex.Message}"); return; } LSLog.LogImportant($"Created Room: {_room.Id}"); _lastRoomId = roomId; RegisterRoomHandlers(); }
/// <summary> /// Unsubscribes <see cref="Room" /> from networked events."/> /// </summary> private void ClearRoomHandlers() { if (_pingThread != null) { _pingThread.Abort(); _pingThread = null; } if (_room == null) { return; } _room.State.networkedEntities.OnAdd -= OnEntityAdd; _room.State.networkedEntities.OnRemove -= OnEntityRemoved; _room.State.networkedUsers.OnAdd -= OnUserAdd; _room.State.networkedUsers.OnRemove -= OnUserRemove; _room.colyseusConnection.OnError -= Room_OnError; _room.colyseusConnection.OnClose -= Room_OnClose; _room.OnStateChange -= OnStateChangeHandler; _room.OnLeave -= OnLeaveRoom; _room = null; _currentNetworkedUser = null; }
/// <summary> /// Creates a new <see cref="ExampleNetworkedEntity"/> with the given prefab, attributes, and <see cref="ColyseusNetworkedEntityView"/>. /// </summary> /// <param name="room">The room the entity will be added to</param> /// <param name="prefab">Prefab you would like to use</param> /// <param name="attributes">Position for the new entity</param> /// <param name="viewToAssign">The provided view that will be assigned to the new <see cref="ExampleNetworkedEntity"/></param> /// <param name="callback">Callback that will be invoked with the newly created <see cref="ExampleNetworkedEntity"/></param> public void CreateNetworkedEntity(ColyseusRoom <ExampleRoomState> room, string prefab, Dictionary <string, object> attributes = null, ColyseusNetworkedEntityView viewToAssign = null, Action <ExampleNetworkedEntity> callback = null) { Dictionary <string, object> updatedAttributes = (attributes != null) ? new Dictionary <string, object>(attributes) : new Dictionary <string, object>(); updatedAttributes.Add("prefab", prefab); CreateNetworkedEntity(room, updatedAttributes, viewToAssign, callback); }
void Awake() { if (Instance == null) { DontDestroyOnLoad(gameObject); Instance = this; } else { Destroy(gameObject); } }
private void OnLeaveRoom(WebSocketCloseCode code) { LSLog.Log("ROOM: ON LEAVE =- Reason: " + code); _pingThread.Abort(); _pingThread = null; _room = null; if (code != WebSocketCloseCode.Normal && !string.IsNullOrEmpty(_lastRoomId)) { JoinRoomId(_lastRoomId); } }
private void OnLeaveRoom(int code) { WebSocketCloseCode closeCode = WebSocketHelpers.ParseCloseCodeEnum(code); LSLog.Log(string.Format("ROOM: ON LEAVE =- Reason: {0} ({1})", closeCode, code)); _pingThread.Abort(); _pingThread = null; _room = null; if (closeCode != WebSocketCloseCode.Normal && !string.IsNullOrEmpty(_lastRoomId)) { JoinRoomId(_lastRoomId); } }
private void Start() { message.text = "Connecting..."; _roomController = GameManager.Instance.RoomController; _room = ColyseusRoom.Instance; _room.onConnect.AddListener(OnConnect); _room.onJoin.AddListener(OnJoin); if (_roomController.Client == null) { GameManager.Instance.InitializeClient(); } else { OnConnect(); } }
/// <summary> /// Creates a new <see cref="ExampleNetworkedEntity"/> attributes and <see cref="ColyseusNetworkedEntityView"/>. /// </summary> /// <param name="room">The room the entity will be added to</param> /// <param name="attributes">Position for the new entity</param> /// <param name="viewToAssign">The provided view that will be assigned to the new <see cref="ExampleNetworkedEntity"/></param> /// <param name="callback">Callback that will be invoked with the newly created <see cref="ExampleNetworkedEntity"/></param> public void CreateNetworkedEntity(ColyseusRoom <ExampleRoomState> room, Dictionary <string, object> attributes = null, ColyseusNetworkedEntityView viewToAssign = null, Action <ExampleNetworkedEntity> callback = null) { try { string creationId = null; if (viewToAssign != null || callback != null) { creationId = Guid.NewGuid().ToString(); if (callback != null) { if (viewToAssign != null) { _creationCallbacks.Add(creationId, (newEntity) => { RegisterNetworkedEntityView(newEntity, viewToAssign); callback.Invoke(newEntity); }); } else { _creationCallbacks.Add(creationId, callback); } } else { _creationCallbacks.Add(creationId, (newEntity) => { RegisterNetworkedEntityView(newEntity, viewToAssign); }); } } _ = room.Send("createEntity", new EntityCreationMessage() { creationId = creationId, attributes = attributes }); } catch (System.Exception err) { LSLog.LogError(err.Message + err.StackTrace); } }
/// <summary> /// Join an existing room or create a new one using <see cref="roomName" /> with no options. /// <para>Locked or private rooms are ignored.</para> /// </summary> public async void JoinOrCreateRoom() { try { LSLog.LogImportant($"Join Or Create Room - Name = {roomName}.... "); // Populate an options dictionary with custom options provided elsewhere Dictionary <string, object> options = new Dictionary <string, object>(); foreach (KeyValuePair <string, object> option in roomOptionsDictionary) { options.Add(option.Key, option.Value); } _room = await _client.JoinOrCreate <ExampleRoomState>(roomName, options); LSLog.LogImportant($"Joined / Created Room: {_room.Id}"); _lastRoomId = _room.Id; RegisterRoomHandlers(); } catch (Exception e) { LSLog.LogError($"Room Controller Error - {e.Message + e.StackTrace}"); } }