/// <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 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();
    }
示例#3
0
    private void CreateView(ExampleNetworkedEntity entity)
    {
        LSLog.LogImportant("print: " + JsonUtility.ToJson(entity));
        ColyseusNetworkedEntityView newView = Instantiate(prefab);

        ExampleManager.Instance.RegisterNetworkedEntityView(entity, newView);
        newView.gameObject.SetActive(true);
    }
示例#4
0
    /// <summary>
    ///     Subscribes the manager to <see cref="room" />'s networked events
    ///     and starts measuring latency to the server.
    /// </summary>
    public virtual void RegisterRoomHandlers()
    {
        LSLog.LogImportant($"sessionId: {_room.SessionId}");

        if (_pingThread != null)
        {
            _pingThread.Abort();
            _pingThread = null;
        }

        _pingThread = new Thread(RunPingThread);
        _pingThread.Start(_room);

        _room.OnLeave += OnLeaveRoom;

        _room.OnStateChange += OnStateChangeHandler;

        _room.OnMessage <ExampleNetworkedUser>("onJoin", currentNetworkedUser =>
        {
            Debug.Log($"Received 'ExampleNetworkedUser' after join/creation call {currentNetworkedUser.id}!");
            Debug.Log(Json.SerializeToString(currentNetworkedUser));

            _currentNetworkedUser = currentNetworkedUser;
        });

        _room.OnMessage <ExampleRFCMessage>("onRFC", _rfc =>
        {
            //Debug.Log($"Received 'onRFC' {_rfc.entityId}!");
            if (_entityViews.Keys.Contains(_rfc.entityId))
            {
                _entityViews[_rfc.entityId].RemoteFunctionCallHandler(_rfc);
            }
        });

        _room.OnMessage <ExamplePongMessage>(0, message =>
        {
            _lastPong    = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
            _serverTime  = message.serverTime;
            _waitForPong = false;
        });

        //Custom game logic
        //_room.OnMessage<YOUR_CUSTOM_MESSAGE>("messageNameInCustomLogic", objectOfTypeYOUR_CUSTOM_MESSAGE => {  });

        //========================
        _room.State.networkedEntities.OnAdd    += OnEntityAdd;
        _room.State.networkedEntities.OnRemove += OnEntityRemoved;

        _room.State.networkedUsers.OnAdd    += OnUserAdd;
        _room.State.networkedUsers.OnRemove += OnUserRemove;

        _room.State.TriggerAll();
        //========================

        _room.colyseusConnection.OnError += Room_OnError;
        _room.colyseusConnection.OnClose += Room_OnClose;
    }
示例#5
0
 private void OnNetworkAdd(ExampleNetworkedEntity entity)
 {
     if (ExampleManager.Instance.HasEntityView(entity.id))
     {
         LSLog.LogImportant("View found! For " + entity.id);
     }
     else
     {
         LSLog.LogImportant("No View found for " + entity.id);
         CreateView(entity);
     }
 }
 private void OnNetworkAdd(ExampleNetworkedEntity entity)
 {
     if (ExampleManager.Instance.HasEntityView(entity.id))
     {
         LSLog.LogImportant("View found! For " + entity.id);
         scoreboardController.EntityAdded(entity); //Already exists in scene which means it has been initialized
     }
     else
     {
         LSLog.LogImportant("No View found for " + entity.id);
         CreateView(entity);
     }
 }
    IEnumerator WaitForConnect()
    {
        if (ExampleManager.Instance.CurrentUser != null && !IsMine)
        {
            yield break;
        }

        while (!ExampleManager.Instance.IsInRoom)
        {
            yield return(0);
        }
        LSLog.LogImportant("HAS JOINED ROOM - CREATING ENTITY");
        ExampleManager.CreateNetworkedEntityWithTransform(new Vector3(0f, 0f, 0f), Quaternion.identity, new Dictionary <string, object>()
        {
            ["prefab"] = "VMEViewPrefab"
        }, this, (entity) => {
            LSLog.LogImportant($"Network Entity Ready {entity.id}");
        });
    }
    /// <summary>
    ///     Callback for when a <see cref="ExampleNetworkedUser" /> is added to a room.
    /// </summary>
    /// <param name="user">The user object</param>
    /// <param name="key">The user key</param>
    private void OnUserAdd(string key, ExampleNetworkedUser user)
    {
        LSLog.LogImportant($"user [{user.__refId} | {user.id} | key {key}] Joined");

        // Add "player" to map of players
        _users.Add(key, user);

        // On entity update...
        user.OnChange += changes =>
        {
            user.updateHash = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString();

            // If the change is for our current user then fire the event with the attributes that changed
            if (ExampleManager.Instance.CurrentUser != null &&
                string.Equals(ExampleManager.Instance.CurrentUser.sessionId, user.sessionId))
            {
                OnCurrentUserStateChanged?.Invoke(user.attributes);
            }
        };
    }
    /// <summary>
    ///     The callback for the event when a <see cref="ExampleNetworkedEntity" /> is added to a room.
    /// </summary>
    /// <param name="entity">The entity that was just added.</param>
    /// <param name="key">The entity's key</param>
    private async void OnEntityAdd(string key, ExampleNetworkedEntity entity)
    {
        LSLog.LogImportant(
            $"Entity [{entity.__refId} | {entity.id}] add: x => {entity.xPos}, y => {entity.yPos}, z => {entity.zPos}");

        _entities.Add(entity.id, entity);

        //Creation ID is only Registered with the owner so only owners callback will be triggered
        if (!string.IsNullOrEmpty(entity.creationId) && _creationCallbacks.ContainsKey(entity.creationId))
        {
            _creationCallbacks[entity.creationId].Invoke(entity);
            _creationCallbacks.Remove(entity.creationId);
        }

        onAddNetworkEntity?.Invoke(entity);

        if (_entityViews.ContainsKey(entity.id) == false && !string.IsNullOrEmpty(entity.attributes["prefab"]))
        {
            await _factory.CreateFromPrefab(entity);
        }
    }
    /// <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}");
        }
    }
示例#11
0
    private IEnumerator WaitForConnect()
    {
        if (ExampleManager.Instance.CurrentUser != null && !IsMine)
        {
            yield break;
        }

        lookCamera.gameObject.SetActive(true);
        while (!ExampleManager.Instance.IsInRoom)
        {
            yield return(0);
        }

        LSLog.LogImportant("HAS JOINED ROOM - CREATING ENTITY");
        ExampleManager.CreateNetworkedEntityWithTransform(transform.position, Quaternion.identity,
                                                          new Dictionary <string, object> {
            ["userName"] = ExampleManager.Instance.UserName
        }, this, entity =>
        {
            userName             = ExampleManager.Instance.UserName;
            userNameDisplay.text = userName;
            ExampleManager.Instance.CurrentNetworkedEntity = entity;
        });
    }
    /// <summary>
    ///     Callback for when a user is removed from a room.
    /// </summary>
    /// <param name="user">The removed user.</param>
    /// <param name="key">The user key.</param>
    private void OnUserRemove(string key, ExampleNetworkedUser user)
    {
        LSLog.LogImportant($"user [{user.__refId} | {user.id} | key {key}] Left");

        _users.Remove(key);
    }
    /// <summary>
    ///     Subscribes the manager to <see cref="room" />'s networked events
    ///     and starts measuring latency to the server.
    /// </summary>
    public virtual void RegisterRoomHandlers()
    {
        LSLog.LogImportant($"sessionId: {_room.SessionId}");

        if (_pingThread != null)
        {
            _pingThread.Abort();
            _pingThread = null;
        }

        _pingThread = new Thread(RunPingThread);
        _pingThread.Start(_room);

        _room.OnLeave += OnLeaveRoom;

        _room.OnStateChange += OnStateChangeHandler;

        _room.OnMessage <ExampleNetworkedUser>("onJoin", currentNetworkedUser =>
        {
            Debug.Log($"Received 'ExampleNetworkedUser' after join/creation call {currentNetworkedUser.id}!");
            Debug.Log(Json.SerializeToString(currentNetworkedUser));

            _currentNetworkedUser = currentNetworkedUser;
        });

        _room.OnMessage <ExampleRFCMessage>("onRFC", _rfc =>
        {
            //Debug.Log($"Received 'onRFC' {_rfc.entityId}!");
            if (_entityViews.Keys.Contains(_rfc.entityId))
            {
                _entityViews[_rfc.entityId].RemoteFunctionCallHandler(_rfc);
            }
        });

        _room.OnMessage <ExamplePongMessage>(0, message =>
        {
            _lastPong    = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
            _serverTime  = message.serverTime;
            _waitForPong = false;
        });

        //Custom game logic
        _room.OnMessage <ShootingGalleryNewTargetLineUpMessage>("newTargetLineUp",
                                                                targets => { onGotTargetLineUp?.Invoke(targets); });

        _room.OnMessage <ShootingGalleryScoreUpdateMessage>("onScoreUpdate",
                                                            scoreUpdate => { onScoreUpdate?.Invoke(scoreUpdate); });

        _room.OnMessage <ShootingGalleryMessage>("beginRoundCountDown", msg => { onBeginRoundCountDown?.Invoke(); });

        _room.OnMessage <ShootingGalleryMessage>("beginRound", msg => { onBeginRound?.Invoke(); });

        _room.OnMessage <ShootingGalleryRoundEndMessage>("onRoundEnd", winner => { onRoundEnd?.Invoke(winner.winner); });

        //========================
        Debug.Log($"Adding OnAdd/OnRemove callbacks for all {_room.State.networkedEntities.Count} entities! ***");
        _room.State.networkedEntities.OnAdd    += OnEntityAdd;
        _room.State.networkedEntities.OnRemove += OnEntityRemoved;

        _room.State.networkedUsers.OnAdd    += OnUserAdd;
        _room.State.networkedUsers.OnRemove += OnUserRemove;

        _room.State.TriggerAll();
        //========================

        _room.colyseusConnection.OnError += Room_OnError;
        _room.colyseusConnection.OnClose += Room_OnClose;
    }
示例#14
0
 public override void OnEntityRemoved()
 {
     base.OnEntityRemoved();
     LSLog.LogImportant("REMOVING ENTITY", LSLog.LogColor.lime);
     Destroy(gameObject);
 }