/** <summary>Spawns an object from the server</summary>
         * <param name="pEvent">The socket event fired from the server</param>
         * <param name="ourClient">The socket reference of our NetworkClient</param>
         * */
        public void OnServerSpawn(SocketIOEvent pEvent, NetworkClient ourClient)
        {
            //Extract Data from Event
            string name = pEvent.data["name"].str;
            string id   = pEvent.data["id"].ToString().RemoveQuotes();
            float  x    = pEvent.data["position"]["x"].f;
            float  y    = pEvent.data["position"]["y"].f;
            float  z    = pEvent.data["position"]["z"].f;

            /** SPAWN SERVER OBJECT
             * > Check if we have a reference to that object.
             * > Find the object we are spawning from our 'serverSpawnables' class.
             * > Set the position of the object to the server's passed position.
             * > Get the <NetworkIdentity> of the spawned object.
             * > Set reference on that NI for its ID and Socket Reference.
             * */
            if (!mMaster.getServerObjects().ContainsKey(id))
            {
                ServerObjectData sod = serverSpawnables.GetObjectByName(name);                 //Find the server object by the name of the object.
                var spawnedObject    = Instantiate(sod.Prefab, mMaster.getNetworkContainer()); //Instantiate the object's prefab as a child of our 'networkContainer'
                spawnedObject.transform.position = new Vector3(x, y, z);
                var ni = spawnedObject.GetComponent <NetworkIdentity>();
                ni.SetControllerID(id);
                ni.SetSocketReference(ourClient);

                //If bullet apply direction as well
                if (name == "Bullet")
                {
                    handleBulletSpawn(pEvent, spawnedObject);
                }

                //Add reference of this object to our 'serverObjects'
                mMaster.getServerObjects().Add(id, ni);
            }
        }
예제 #2
0
        public override void Start()
        {
            base.Start();

            networkIdentities  = new List <NetworkIdentity>();
            ApplicationVersion = Application.version;
            timer          = 0;
            pingTimer      = 0;
            isCountingPing = false;

            On(NetworkTags.OPEN, (E) => {
                Debug.Log("Connection made to server");
                OnConnected.Invoke(E);
            });

            On(NetworkTags.CLOSE, (E) => {
                Debug.Log("On Close!");
                isConnected = false;
            });

            On(NetworkTags.REGISTER, (E) => {
                ClientID = E.data["id"].ToString().RemoveQuotes();
                Debug.LogFormat("Registering: Our Client Is ({0})", ClientID);

                VersionData vd = new VersionData();
                vd.Username    = PlayerInformation.Instance.PlayerName;
                vd.version     = ApplicationVersion;
                vd.IsAdmin     = PlayerInformation.Instance.IsAdmin;
                Emit(NetworkTags.SERVER_VALIDATION, new JSONObject(JsonUtility.ToJson(vd)));
            });

            On(NetworkTags.SPAWN, (E) => {
                OnSpawn.Invoke(E);
                string username = E.data["username"].ToString();
                string id       = E.data["id"].ToString().RemoveQuotes();
                bool admin      = E.data["isAdmin"].b;
                float x         = E.data["position"]["x"].f;
                float y         = E.data["position"]["y"].f;
                Debug.LogFormat("Spawning: Client ({0}:{1}) they are an admin? {2}", username, id, admin);

                if (!networkIdentities.Any(obj => obj.GetID() == id))
                {
                    var player = Instantiate(playerPrefab, playerContainer);
                    player.transform.position = PlayerInformation.Instance.SpawnLocation;
                    var ni = player.GetComponent <NetworkIdentity>();
                    ni.SetControllerID(id);
                    ni.SetSocketReference(this);

                    //var pm = player.GetComponent<PlayerManager>();
                    //pm.SetUsername(username);
                    //pm.SetIsAdmin(admin);

                    //Check for game events involving adming players

                    /*if (ni.IsControlling() && admin) {
                     *  foreach (var item in removeableAreas) {
                     *      item.SetActive(false);
                     *  }
                     * }*/

                    if (ni.IsControlling())
                    {
                        PlayerInformation.Instance.SetVirtualCamera(ni.transform);
                    }
                    else
                    {
                        //Remove Rigid body from non controlled players
                        DestroyImmediate(player.GetComponent <Rigidbody2D>());
                        List <Project.Player.Player_FlipJoe.AbstractBehaviour> behaviours = player.GetComponents <Project.Player.Player_FlipJoe.AbstractBehaviour>().ToList();
                        while (behaviours.Count > 0)
                        {
                            Project.Player.Player_FlipJoe.AbstractBehaviour behaviour = behaviours[0];
                            DestroyImmediate(behaviour);
                            behaviours.Remove(behaviour);
                        }
                    }
                    networkIdentities.Add(ni);
                }
            });

            On(NetworkTags.DISCONNECT, (E) => {
                string id = E.data["id"].ToString().RemoveQuotes();
                Debug.LogFormat("Disconnected: Client ({0})", id);

                List <NetworkIdentity> clientObjects = networkIdentities.Where(x => x.GetID() == id).ToList();
                foreach (var item in clientObjects)
                {
                    networkIdentities.Remove(item);
                    DestroyImmediate(item.gameObject);
                }

                OnDisconnected.Invoke(E);
            });

            On(NetworkTags.UPDATE_POSITION, (E) => {
                //Debug.LogFormat("JSON DATA: {0}", E.data.ToString());
                string id = E.data["id"].ToString().RemoveQuotes();
                float x   = E.data["position"]["x"].f;
                float y   = E.data["position"]["y"].f;
                //Debug.LogFormat("Updating position for player {0}:({1},{2})", id, x, y);
                NetworkIdentity ni    = networkIdentities.Single(i => i.GetID() == id);
                ni.transform.position = new Vector3(x, y, 0);
            });

            On(NetworkTags.CHAT, (E) => {
                OnChat.Invoke(E);
            });

            On(NetworkTags.ANIMATOR_STATE, (E) => {
                OnAnimationUpdate.Invoke(E);
            });

            On(NetworkTags.SERVER_SPAWN, (E) => {
                string name  = E.data["name"].str;
                string id    = E.data["id"].ToString().RemoveQuotes();
                float x      = E.data["position"]["x"].f;
                float y      = E.data["position"]["y"].f;
                bool isRight = E.data["isRight"].b;
                Debug.LogFormat("Server wants us to spawn a '{0}'", name);

                if (!networkIdentities.Any(obj => obj.GetID() == id))
                {
                    ServerObjectData sod             = serverObjects.GetObjectByName(name);
                    var spawnedObject                = Instantiate(sod.Prefab, serverContainer);
                    spawnedObject.transform.position = new Vector3(x, y, 0);
                    var ni = spawnedObject.GetComponent <NetworkIdentity>();
                    ni.SetControllerID(id);
                    ni.SetSocketReference(this);

                    Vector3 scale = spawnedObject.transform.localScale;
                    scale.x      *= (isRight) ? 1 : -1; //Flip x if facing other direction
                    spawnedObject.transform.localScale = scale;

                    //If bullet apply direction as well
                    if (name == "Bullet")
                    {
                        float directionX = E.data["direction"]["x"].f;
                        float directionY = E.data["direction"]["y"].f;

                        float rot = Mathf.Atan2(directionY, directionX) * Mathf.Rad2Deg;
                        Debug.LogFormat("Rotation Value {0}", rot);
                        float offset                     = (isRight) ? 0 : 180;
                        Vector3 currentRotation          = new Vector3(0, 0, rot - offset);
                        spawnedObject.transform.rotation = Quaternion.Euler(currentRotation);
                    }

                    networkIdentities.Add(ni);
                }
            });

            On(NetworkTags.SERVER_UNSPAWN, (E) => {
                string id          = E.data["id"].ToString().RemoveQuotes();
                NetworkIdentity ni = networkIdentities.Single(i => i.GetID() == id);
                networkIdentities.Remove(ni);
                DestroyImmediate(ni.gameObject);
            });

            On(NetworkTags.SERVER_VALIDATION, (E) => {
                Debug.Log("Close down socket");
                LoaderManager.Instance.LoadLevel(SceneList.LOGIN, (LevelName) => {
                    LoaderManager.Instance.UnLoadLevel(SceneList.ONLINE);
                    ApplicationManager.Instance.ShowIntroGraphics();
                });
                Close();
            });

            On(NetworkTags.PING, (E) => {
                //Ping from server
                isCountingPing = false;
                pingText.text  = string.Format("Ping: {0}", (pingTimer * 100).ToString("F0"));
                pingTimer      = 0;
            });

            On(NetworkTags.UPDATE_STATS, (E) => {
                OnUpdateStats.Invoke(E);
            });

            On(NetworkTags.GENERAL_EVENT, (E) => {
                OnGeneralEvent.Invoke(E);
            });

            On(NetworkTags.LOAD_REALM, (E) => {
                float realm    = E.data["realm"].n;
                float oldRealm = E.data["oldRealm"].n;

                Debug.LogFormat("Leaving Realm ({0}) and Entering Realm ({1})", oldRealm, realm);

                if (oldRealm != -1)
                {
                    LoaderManager.Instance.UnLoadLevel(SceneList.GetMapByIndex((int)oldRealm));
                }

                PlayerInformation.Instance.OldRealm     = (int)oldRealm;
                PlayerInformation.Instance.CurrentRealm = (int)realm;

                LoaderManager.Instance.LoadLevel(SceneList.GetMapByIndex((int)realm), (Level) => {
                    //MapData md = FindObjectsOfType<MapData>().First(x => x.GetRealmID() == PlayerInformation.Instance.CurrentRealm);
                    //PlayerInformation.Instance.SpawnLocation = md.GetStartingPosition(PlayerInformation.Instance.OldRealm);

                    //NetworkIdentity ni = networkIdentities.Single(obj => obj.GetID() == ClientID);
                    //ni.transform.position = PlayerInformation.Instance.SpawnLocation;
                }, true);
            });

            On(NetworkTags.SERVER_VALIDATION_COMPLETE, (E) => {
                OnValidatedToServer.Invoke(this);
            });

            On(NetworkTags.JOIN_LOBBY, (E) => {
                OnJoinLobby.Invoke();
            });

            On(NetworkTags.LOBBY_UPDATE, (E) => {
                OnLobbyUpdate.Invoke(E);
            });

            On(NetworkTags.START_GAME, (E) => {
                string id   = E.data["id"].ToString().RemoveQuotes();
                string team = E.data["team"].ToString().RemoveQuotes();

                PlayerInformation.Instance.CurrentTeam = (team == "blue") ? Team.Blue : Team.Orange;
                Debug.LogFormat("ID: {0} | {1} | {2}", id, team, PlayerInformation.Instance.CurrentTeam);

                LoaderManager.Instance.LoadLevel(SceneList.GetMapByIndex(2), (Val) => {
                    LoaderManager.Instance.UnLoadLevel(SceneList.GAME_LOBBY);

                    Debug.LogFormat("ID: {0} | {1}", ClientID, PlayerInformation.Instance.CurrentTeam);

                    MapData md = FindObjectOfType <MapData>();
                    md.SetBackgroundColour();
                    Vector3 pos           = md.GetStartingPosition(PlayerInformation.Instance.CurrentTeam);
                    NetworkIdentity ni    = networkIdentities.Single(i => i.GetID() == ClientID);
                    ni.transform.position = pos;
                });
            });
        }
예제 #3
0
        private void setupEvents()
        {
            On("open", (E) =>
            {
                Debug.Log("Connection made to the server");
            });

            On("register", (E) =>
            {
                ClientID = E.data["id"].ToString().RemoveQuotes();
                Debug.LogFormat("Our Clent's ID ({0})", ClientID);
            });

            On("spawn", (E) =>
            {
                string id          = E.data["id"].ToString().RemoveQuotes();
                GameObject go      = Instantiate(playerPrefab, networkContainer);
                go.name            = string.Format("Player ({0})", id);
                NetworkIdentity n1 = go.GetComponent <NetworkIdentity>();
                n1.SetControllerID(id);
                n1.SetSocketReference(this);
                serverObjects.Add(id, n1);
            });
            On("disconnected", (E) =>
            {
                string id     = E.data["id"].ToString().RemoveQuotes();
                GameObject go = serverObjects[id].gameObject;
                Destroy(go);
                serverObjects.Remove(id);
            });

            On("updatePosition", (E) =>
            {
                string id = E.data["id"].ToString().RemoveQuotes();
                float x   = E.data["position"]["x"].f;
                float y   = E.data["position"]["y"].f;
                float z   = E.data["position"]["z"].f;

                NetworkIdentity n1    = serverObjects[id];
                n1.transform.position = new Vector3(x, y, z);
            });

            On("serverSpawn", (E) =>
            {
                string name = E.data["name"].str;
                string id   = E.data["id"].ToString().RemoveQuotes();
                float x     = E.data["position"]["x"].f;
                float y     = E.data["position"]["y"].f;
                float z     = E.data["position"]["z"].f;
                Debug.LogFormat("Server wants us to spawn a (0)", name);
                // Vector3 aux = new Vector3(x, y, z);
                // var actualPosition = new GameObject();
                // actualPosition.transform.position = aux;
                if (!serverObjects.ContainsKey(id))
                {
                    ServerObjectData sod             = serverSpawnables.GetObjectByName(name);
                    var spawnedObject                = Instantiate(sod.prefab, networkContainer);
                    spawnedObject.transform.position = new Vector3(x, y, z);
                    var ni = spawnedObject.GetComponent <NetworkIdentity>();
                    ni.SetControllerID(id);
                    ni.SetSocketReference(this);

                    if (name == "Shell")
                    {
                        float directionX  = E.data["direction"]["x"].f;
                        float directionY  = E.data["direction"]["y"].f;
                        float directionZ  = E.data["direction"]["z"].f;
                        float inclinacion = (directionY - y) / (directionX - x);
                        //something with atan2

                        float rot = Mathf.Atan2(directionX, directionY) * Mathf.Rad2Deg;
                        Vector3 currentRotation = new Vector3(0, 0, rot - 90);

                        spawnedObject.transform.rotation = Quaternion.Euler(currentRotation);
                    }

                    serverObjects.Add(id, ni);
                }
            });
            On("serverUnspawn", (E) =>
            {
                string id          = E.data["id"].ToString().RemoveQuotes();
                NetworkIdentity n1 = serverObjects[id];
                serverObjects.Remove(id);
                DestroyImmediate(n1.gameObject);
            });
        }
        // Update is called once per frame
        // public override void Update()
        // {
        //     base.Update();
        // }
        private void SetupEvents()
        {
            // Initial connection will connect just once, even if console displays TWO logs.
            io.On("open", (e) => {
                Debug.Log("connection made to server");
            });

            io.On("register", (e) => {
                ClientID = new JSONObject(e.data)["id"].str;
                Debug.LogFormat("Our Client's Id is ({0})", ClientID);
            });

            io.On("spawn", (e) => {
                // handling all spawned players
                string id = new JSONObject(e.data)["id"].str;

                GameObject go      = Instantiate(playerGO, networkContainer);
                go.name            = string.Format("Player ({0})", id);
                NetworkIdentity ni = go.GetComponent <NetworkIdentity>();
                ni.SetControllerID(id);
                ni.SetSocketReference(io.socketIO);
                serverObjects.Add(id, ni);
            });

            io.On("disconnected", (e) => {
                string id = new JSONObject(e.data)["id"].str;
                Debug.Log("player disconnected");
                GameObject go = serverObjects[id].gameObject;
                Destroy(go); // remove GO from game
                serverObjects.Remove(id);
            });

            io.On("updateRotation", (e) => {
                JSONObject data    = new JSONObject(e.data);
                string id          = data["id"].ToString().RemoveQuotes();
                float weaponRot    = data["weaponRotation"].f;
                bool flipped       = data["playerFlipped"].b;
                NetworkIdentity ni = serverObjects[id];
                // Debug.Log("updating other rotations");
                ni.GetComponent <PlayerManager>().SetWeaponRotation(weaponRot);
            });

            io.On("updatePosition", (e) => {
                JSONObject data       = new JSONObject(e.data);
                string id             = data["id"].ToString().RemoveQuotes();
                float x               = data["position"]["x"].f;
                float y               = data["position"]["y"].f;
                NetworkIdentity ni    = serverObjects[id];
                ni.transform.position = new Vector3(x, y, 0);
            });

            io.On("serverSpawn", (e) => {
                JSONObject data = new JSONObject(e.data);
                string name     = data["name"].str;
                string id       = data["id"].ToString().RemoveQuotes();
                float x         = data["position"]["x"].f;
                float y         = data["position"]["y"].f;
                if (!serverObjects.ContainsKey(id))
                {
                    // Debug.LogFormat("Server wants to spawn '{0}'", name);
                    ServerObjectData sod           = serverSpawnables.GetObjectByName(name);
                    var spawnObject                = Instantiate(sod.Prefab, networkContainer);
                    spawnObject.transform.position = new Vector3(x, y, 0);
                    NetworkIdentity ni             = spawnObject.GetComponent <NetworkIdentity>();
                    ni.SetControllerID(id);
                    ni.SetSocketReference(io.socketIO);

                    // if projectile apply direction as well
                    if (name == "Arrow_Regular")
                    {
                        float directionX = data["direction"]["x"].f;
                        float directionY = data["direction"]["y"].f;
                        string activator = data["activator"].ToString().RemoveQuotes();
                        float speed      = data["speed"].f;

                        float rot = Mathf.Atan2(directionY, directionX) * Mathf.Rad2Deg;
                        Vector3 currentRotation        = new Vector3(0, 0, rot + 180);
                        spawnObject.transform.rotation = Quaternion.Euler(currentRotation);

                        WhoActivatedMe whoActivatedMe = spawnObject.GetComponent <WhoActivatedMe>();
                        whoActivatedMe.SetActivator(activator);

                        Projectile projectile = spawnObject.GetComponent <Projectile>();
                        projectile.Direction  = new Vector2(directionX, directionY);
                        projectile.Speed      = speed;
                    }
                    serverObjects.Add(id, ni);
                }
            });
            io.On("serverDespawn", (e) => {
                string id          = new JSONObject(e.data)["id"].str;
                NetworkIdentity ni = serverObjects[id];
                serverObjects.Remove(id);
                Destroy(ni.gameObject);
            });
            io.On("playerDied", (e) => {
                string id          = new JSONObject(e.data)["id"].str;
                NetworkIdentity ni = serverObjects[id];
                ni.gameObject.SetActive(false);
            });
            io.On("playerRespawn", (e) => {
                JSONObject data       = new JSONObject(e.data);
                string id             = data["id"].ToString().RemoveQuotes();
                float x               = data["position"]["x"].f;
                float y               = data["position"]["y"].f;
                NetworkIdentity ni    = serverObjects[id];
                ni.transform.position = new Vector3(x, y, 0);
                ni.gameObject.SetActive(true);
            });
            io.On("loadGame", (e) => {
                SceneManagementManager.Instance.LoadLevel(levelName: SceneList.LEVEL, onLevelLoaded: (levelName) => {
                    SceneManagementManager.Instance.UnLoadLevel(SceneList.MAIN_MENU);
                });
            });
        }
예제 #5
0
        private void setupEvents()
        {
            On("open", (E) => {
                Debug.Log("Connection made to the server");
            });

            On("register", (E) => {
                ClientID = E.data["id"].ToString().RemoveQuotes();
                Debug.LogFormat("Our Client's ID ({0})", ClientID);
            });

            On("spawn", (E) => {
                //Handling all spawning all players
                //Passed Data
                string id = E.data["id"].ToString().RemoveQuotes();

                GameObject go      = Instantiate(playerPrefab, networkContainer);
                go.name            = string.Format("Player ({0})", id);
                NetworkIdentity ni = go.GetComponent <NetworkIdentity>();
                ni.SetControllerID(id);
                ni.SetSocketReference(this);
                serverObjects.Add(id, ni);
            });

            On("disconnected", (E) => {
                string id = E.data["id"].ToString().RemoveQuotes();

                GameObject go = serverObjects[id].gameObject;
                Destroy(go);              //Remove from game
                serverObjects.Remove(id); //Remove from memory
            });

            On("updatePosition", (E) => {
                string id = E.data["id"].ToString().RemoveQuotes();
                float x   = E.data["position"]["x"].f;
                float y   = E.data["position"]["y"].f;

                NetworkIdentity ni    = serverObjects[id];
                ni.transform.position = new Vector3(x, y, 0);
            });

            On("updateRotation", (E) => {
                string id            = E.data["id"].ToString().RemoveQuotes();
                float tankRotation   = E.data["tankRotation"].f;
                float barrelRotation = E.data["barrelRotation"].f;

                NetworkIdentity ni            = serverObjects[id];
                ni.transform.localEulerAngles = new Vector3(0, 0, tankRotation);
                ni.GetComponent <PlayerManager>().SetRotation(barrelRotation);
            });

            On("updateAI", (E) => {
                string id            = E.data["id"].ToString().RemoveQuotes();
                float x              = E.data["position"]["x"].f;
                float y              = E.data["position"]["y"].f;
                float tankRotation   = E.data["tankRotation"].f;
                float barrelRotation = E.data["barrelRotation"].f;

                NetworkIdentity ni = serverObjects[id];
                if (ni.gameObject.activeInHierarchy)
                {
                    StartCoroutine(AIPositionSmoothing(ni.transform, new Vector3(x, y, 0)));
                    ni.GetComponent <AIManager>().SetTankRotation(tankRotation);
                    ni.GetComponent <AIManager>().SetBarrelRotation(barrelRotation);
                }
            });

            On("serverSpawn", (E) => {
                string name = E.data["name"].str;
                string id   = E.data["id"].ToString().RemoveQuotes();
                float x     = E.data["position"]["x"].f;
                float y     = E.data["position"]["y"].f;
                Debug.LogFormat("Server wants us to spawn a '{0}'", name);

                if (!serverObjects.ContainsKey(id))
                {
                    ServerObjectData sod             = serverSpawnables.GetObjectByName(name);
                    var spawnedObject                = Instantiate(sod.Prefab, networkContainer);
                    spawnedObject.transform.position = new Vector3(x, y, 0);
                    var ni = spawnedObject.GetComponent <NetworkIdentity>();
                    ni.SetControllerID(id);
                    ni.SetSocketReference(this);

                    //If bullet apply direction as well
                    if (name == "Bullet")
                    {
                        float directionX = E.data["direction"]["x"].f;
                        float directionY = E.data["direction"]["y"].f;
                        string activator = E.data["activator"].ToString().RemoveQuotes();
                        float speed      = E.data["speed"].f;

                        float rot = Mathf.Atan2(directionY, directionX) * Mathf.Rad2Deg;
                        Vector3 currentRotation          = new Vector3(0, 0, rot - 90);
                        spawnedObject.transform.rotation = Quaternion.Euler(currentRotation);

                        WhoActivatedMe whoActivatedMe = spawnedObject.GetComponent <WhoActivatedMe>();
                        whoActivatedMe.SetActivator(activator);

                        Projectile projectile = spawnedObject.GetComponent <Projectile>();
                        projectile.Direction  = new Vector2(directionX, directionY);
                        projectile.Speed      = speed;
                    }

                    serverObjects.Add(id, ni);
                }
            });

            On("serverUnspawn", (E) => {
                string id          = E.data["id"].ToString().RemoveQuotes();
                NetworkIdentity ni = serverObjects[id];
                serverObjects.Remove(id);
                DestroyImmediate(ni.gameObject);
            });

            On("playerDied", (E) => {
                string id          = E.data["id"].ToString().RemoveQuotes();
                NetworkIdentity ni = serverObjects[id];
                if (ni.GetComponent <AIManager>())
                {
                    ni.GetComponent <AIManager>().StopCoroutines();
                }

                ni.gameObject.SetActive(false);
            });

            On("playerRespawn", (E) => {
                string id             = E.data["id"].ToString().RemoveQuotes();
                float x               = E.data["position"]["x"].f;
                float y               = E.data["position"]["y"].f;
                NetworkIdentity ni    = serverObjects[id];
                ni.transform.position = new Vector3(x, y, 0);
                ni.gameObject.SetActive(true);
            });

            On("loadGame", (E) => {
                Debug.Log("Switching to game");
                SceneManagementManager.Instance.LoadLevel(SceneList.LEVEL, (levelName) => {
                    SceneManagementManager.Instance.UnLoadLevel(SceneList.MAIN_MENU);
                });
            });

            On("lobbyUpdate", (E) => {
                OnGameStateChange.Invoke(E);
            });
        }
예제 #6
0
        private void SetupEvents()
        {
            On("open", (E) => {
                Debug.Log("Connection made to the server");
            });
            On("register", (E) => {
                ClientID = E.data["id"].ToString().RemoveQuotes();
                Debug.LogFormat("Our client's ID {0}", ClientID);
            });
            On("spawn", (E) => {
                //Spawn every players
                string id             = E.data["id"].ToString().RemoveQuotes();
                GameObject go         = Instantiate(playerPrefab, networkContainer);
                int spawnNum          = Random.Range(0, 4);
                go.transform.position = spawnPoint[spawnNum].position;
                go.name            = string.Format("Player {0}", id);
                NetworkIdentity ni = go.GetComponent <NetworkIdentity>();
                ni.SetControllerID(id);
                ni.SetSocketReference(this);
                serverObjects.Add(id, ni);
            });
            On("disconnected", (E) => {
                string id = E.data["id"].ToString().RemoveQuotes();

                GameObject go = serverObjects[id].gameObject;
                Destroy(go);              //Remove gameobject from game
                serverObjects.Remove(id); //Remove id from memory
            });
            On("updatePosition", (E) => {
                string id             = E.data["id"].ToString().RemoveQuotes();
                float x               = E.data["position"]["x"].JSONToFloat();
                float y               = E.data["position"]["y"].JSONToFloat();
                float z               = E.data["position"]["z"].JSONToFloat();
                NetworkIdentity ni    = serverObjects[id];
                ni.transform.rotation = Quaternion.Euler(0, float.Parse(E.data["rotation"].str), 0);
                ni.transform.position = new Vector3(x, y, z);
            });
            //Need to replace with a pool
            On("serverSpawn", (E) => {
                string name = E.data["name"].str;
                string id   = E.data["id"].ToString().RemoveQuotes();
                float x     = E.data["position"]["x"].JSONToFloat();
                float y     = E.data["position"]["y"].JSONToFloat();
                float z     = E.data["position"]["z"].JSONToFloat();
                Debug.LogFormat("Server wants us to spawn a '{0}' with id '{1}'", name, id);

                if (!serverObjects.ContainsKey(id))
                {
                    ServerObjectData sod             = serverSpawnables.GetObjectByName(name);
                    var spawnedObject                = Instantiate(sod.Prefab, networkContainer);
                    spawnedObject.transform.position = new Vector3(x, y, z);
                    var ni = spawnedObject.GetComponent <NetworkIdentity>();
                    ni.SetControllerID(id);
                    ni.SetSocketReference(this);

                    if (name == "Bullet")
                    {
                        float directionX                 = E.data["direction"]["x"].JSONToFloat();
                        float directionY                 = E.data["direction"]["y"].JSONToFloat();
                        float directionZ                 = E.data["direction"]["z"].JSONToFloat();
                        string activator                 = E.data["activator"].ToString().RemoveQuotes();
                        float speed                      = E.data["speed"].JSONToFloat();
                        GameObject activatorGO           = serverObjects[activator].gameObject;
                        spawnedObject.transform.rotation = serverObjects[activator].gameObject.transform.rotation;
                        WhoActivatedMe whoActivatedMe    = spawnedObject.GetComponent <WhoActivatedMe>();
                        whoActivatedMe.WhoActivateMe     = activator;
                        activatorGO.GetComponent <PlayerManager>().ShootingEffects();
                        Projectile projectile = spawnedObject.GetComponent <Projectile>();
                        projectile.Direction  = new Vector3(directionX, directionY, directionZ);
                        projectile.Speed      = speed;
                    }

                    serverObjects.Add(id, ni);
                }
            });
            On("serverUnspawn", (E) => {
                string id          = E.data["id"].ToString().RemoveQuotes();
                NetworkIdentity ni = serverObjects[id];
                serverObjects.Remove(id);
                DestroyImmediate(ni.gameObject);
            });
            On("playerDied", (E) => {
                string id          = E.data["id"].ToString().RemoveQuotes();
                NetworkIdentity ni = serverObjects[id];
                if (id == ClientID)
                {
                    imageEffectScript.IsDead = true;
                }
                ni.gameObject.SetActive(false);
            });
            On("playerRespawn", (E) => {
                string id = E.data["id"].ToString().RemoveQuotes();
                if (id == ClientID)
                {
                    imageEffectScript.IsDead = false;
                }
                NetworkIdentity ni    = serverObjects[id];
                int spawnNum          = Random.Range(0, 4);
                ni.transform.position = spawnPoint[spawnNum].position;
                ni.gameObject.SetActive(true);
            });
        }
예제 #7
0
        private void SetUpEvents()
        {
            //open prints two times, but this is bug with the socket.io asset
            //the connection does not get duplicated so it does not matter much.
            On("open", (e) =>
            {
                Debug.Log("Connection Made with Server");
            });

            On("register", (e) =>
            {
                ClientID = e.data["id"].ToString().RemoveQuotes();//.RemoveQuotes();

                Debug.LogFormat("Our Client's ID is ({0})", ClientID);
            });

            On("spawn", (e) =>
            {
                string id = e.data["id"].ToString().RemoveQuotes();

                GameObject go = Instantiate(playerPrefab, networkContainer);
                go.name       = string.Format("Player ({0})", id);
                //Network Identity: NI : ni
                NetworkIdentity ni = go.GetComponent <NetworkIdentity>();
                ni.SetControllerID(id);
                ni.SetSocketReference(this);
                serverObjects.Add(id, ni);
            });

            On("disconnected", (e) =>
            {
                string id = e.data["id"].ToString().RemoveQuotes();

                GameObject go = serverObjects[id].gameObject;
                Destroy(go);
                serverObjects.Remove(id);
            });

            On("updatePosition", (e) =>
            {
                string id = e.data["id"].ToString().RemoveQuotes();
                float x   = e.data["position"]["x"].f;
                float y   = e.data["position"]["y"].f;

                NetworkIdentity ni    = serverObjects[id];
                ni.transform.position = new Vector3(x, y, 0);
            });

            On("updateRotation", (e) =>
            {
                string id = e.data["id"].ToString().RemoveQuotes();

                float tankRotation   = e.data["tankRotation"].f;
                float barrelRotation = e.data["barrelRotation"].f;

                NetworkIdentity ni            = serverObjects[id];
                ni.transform.localEulerAngles = new Vector3(0, 0, tankRotation);
                ni.GetComponent <PlayerManager>().SetRotation(barrelRotation);
            });

            On("serverSpawn", (e) =>
            {
                string name = e.data["name"].str;
                string id   = e.data["id"].ToString().RemoveQuotes();
                float x     = e.data["position"]["x"].f;
                float y     = e.data["position"]["y"].f;
                Debug.LogFormat("Server wants us to spawn a '{0}'", name);

                if (!serverObjects.ContainsKey(id))
                {
                    ServerObjectData sod             = serverSpawnables.GetObjectByName(name);
                    var spawnedObject                = Instantiate(sod.Prefab, networkContainer);
                    spawnedObject.transform.position = new Vector3(x, y, 0);
                    var ni = spawnedObject.GetComponent <NetworkIdentity>();
                    ni.SetControllerID(id);
                    ni.SetSocketReference(this);

                    //If bullet, apply direction as well
                    if (name == "Bullet")
                    {
                        float directionX = e.data["direction"]["x"].f;
                        float directionY = e.data["direction"]["y"].f;

                        float rot = Mathf.Atan2(directionY, directionX) * Mathf.Rad2Deg;
                        Vector3 currentRotation          = new Vector3(0, 0, rot - 90);
                        spawnedObject.transform.rotation = Quaternion.Euler(currentRotation);
                    }

                    serverObjects.Add(id, ni);
                }
            });

            On("serverUnspawn", (e) =>
            {
                string id          = e.data["id"].ToString().RemoveQuotes();
                NetworkIdentity ni = serverObjects[id];
                serverObjects.Remove(id);
                DestroyImmediate(ni.gameObject);
            });
        }