/// <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>
        ///     Create a match making request
        /// </summary>
        /// <param name="method">The type of request we're making (join, create, etc)</param>
        /// <param name="roomName">The name of the room we're trying to match</param>
        /// <param name="options">Dictionary of options to use in the match making process</param>
        /// <param name="headers">Dictionary of headers to pass to the server</param>
        /// <typeparam name="T">Type of <see cref="ColyseusRoom{T}" /> we want to match with</typeparam>
        /// <returns><see cref="ColyseusRoom{T}" /> we have matched with via async task</returns>
        /// <exception cref="Exception">Thrown if there is a network related error</exception>
        /// <exception cref="CSAMatchMakeException">Thrown if there is an error in the match making process on the server side</exception>
        protected async Task <ColyseusRoom <T> > CreateMatchMakeRequest <T>(string method, string roomName,
                                                                            Dictionary <string, object> options, Dictionary <string, string> headers)
        {
            if (options == null)
            {
                options = new Dictionary <string, object>();
            }

            if (headers == null)
            {
                headers = new Dictionary <string, string>();
            }

            string json = await ColyseusRequest.Request("POST", $"matchmake/{method}/{roomName}", options, headers);

            LSLog.Log($"Server Response: {json}");
            ColyseusMatchMakeResponse response =
                JsonUtility.FromJson <ColyseusMatchMakeResponse>(json /*req.downloadHandler.text*/);

            if (response == null)
            {
                throw new Exception($"Error with request: {json}");
            }

            if (!string.IsNullOrEmpty(response.error))
            {
                throw new CSAMatchMakeException(response.code, response.error);
            }

            return(await ConsumeSeatReservation <T>(response, headers));
        }
        public static async Task <string> Request(string uriMethod, string uriPath, Dictionary <string, object> options = null, Dictionary <string, string> headers = null)
        {
            UriBuilder uriBuilder = new UriBuilder(_serverSettings.WebRequestEndpoint);

            uriBuilder.Path = uriPath;

            UnityWebRequest req = new UnityWebRequest();

            req.method = uriMethod;
            req.url    = uriBuilder.Uri.ToString();
            LSLog.Log($"Requesting from URL: {req.url}");
            if (options != null)
            {
                // Send JSON options on request body
                MemoryStream jsonBodyStream = new MemoryStream();
                Json.Serialize(options, jsonBodyStream); //TODO: Replace GameDevWare serialization

                req.uploadHandler = new UploadHandlerRaw(jsonBodyStream.ToArray())
                {
                    contentType = "application/json"
                };
            }

            foreach (KeyValuePair <string, string> pair in _serverSettings.HeadersDictionary)
            {
                req.SetRequestHeader(pair.Key, pair.Value);
            }

            if (headers != null)
            {
                foreach (KeyValuePair <string, string> header in headers)
                {
                    req.SetRequestHeader(header.Key, header.Value);
                }
            }

            req.downloadHandler = new DownloadHandlerBuffer();
            await req.SendWebRequest();

            if (req.isNetworkError || req.isHttpError)
            {
                if (_serverSettings.useSecureProtocol)
                {
                    //We failed to make this call with a secure protocol, try with non-secure and if that works we'll stick with it
                    _serverSettings.useSecureProtocol = false;
                    LSLog.LogError($"Failed to make request to {req.url} with secure protocol, trying again without!");
                    return(await Request(uriMethod, uriPath, options, headers));
                }
                else
                {
                    throw new Exception(req.error);
                }
            }

            return(req.downloadHandler.text);
        }
示例#4
0
    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);
        }
    }
    protected override void Update()
    {
        base.Update();

        if (!HasInit || !IsMine)
        {
            return;
        }

        groundedPlayer = controller.isGrounded;
        if (groundedPlayer && playerVelocity.y < 0)
        {
            playerVelocity.y = 0f;
        }

        Vector3 move = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));

        controller.Move(move * Time.deltaTime * playerSpeed);

        if (move != Vector3.zero)
        {
            gameObject.transform.forward = move;
        }

        // Changes the height position of the player..
        if (Input.GetButtonDown("Jump") && groundedPlayer)
        {
            playerVelocity.y += Mathf.Sqrt(jumpHeight * -3.0f * gravityValue);
        }

        playerVelocity.y += gravityValue * Time.deltaTime;
        controller.Move(playerVelocity * Time.deltaTime);

        if (Input.GetKeyDown(KeyCode.F))
        {
            LSLog.Log("fire weapon key");
            ExampleManager.RFC(state.id, "FireWeaponRFC", new object[] { new ExampleVector3Obj(transform.forward), "aWeapon" });
        }
    }