/** <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);
            }
        }
Exemplo n.º 2
0
        public void fireBullet()
        {
            shootingCooldown.StartCooldown();

            //Define Bullet
            bulletData.activator  = NetworkClient.ClientID;
            bulletData.position.x = bulletSpawnPoint.position.x.TwoDecimals();
            bulletData.position.y = bulletSpawnPoint.position.y.TwoDecimals();
            bulletData.position.z = bulletSpawnPoint.position.z.TwoDecimals();

            bulletData.direction.x = bulletSpawnPoint.up.x;
            bulletData.direction.y = bulletSpawnPoint.up.y;
            bulletData.direction.z = bulletSpawnPoint.up.z;

            //Send Bullet

            //If we are connected to the server...
            if (mMaster.ourClientIsConnected)
            {
                mMaster.getNetworkIdentity().GetSocket().Emit("fireBullet", new JSONObject(JsonUtility.ToJson(bulletData)));
            }
            else
            {
                float speed = 0.5f;

                ServerObjectData sod = mMaster.OfflineSpawnables.GetObjectByName("Bullet");
                var spawnedObject    = Instantiate(sod.Prefab, mMaster.OfflineContainer);
                spawnedObject.transform.position = new Vector3(bulletData.position.x, bulletData.position.y, bulletData.position.z);

                //Set parameters so that this bullet does not hit its creator.
                WhoActivatedMe whoActivatedMe = spawnedObject.GetComponent <WhoActivatedMe>();
                whoActivatedMe.SetActivator(transform.name);

                //Set the direction and speed of the projectile.
                Projectile projectile = spawnedObject.GetComponent <Projectile>();
                projectile.Direction = transform.forward;
                projectile.Speed     = speed;
            }
        }
Exemplo n.º 3
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;
                });
            });
        }
Exemplo n.º 4
0
        private void setupEvent()
        {
            //Eventio is a callback give by the socket
            //Whatever event we are generate over the server all will be revicered our here

            /*
             *  Here On("Event name",(E)=>{}) will get the response from server to client
             *  where as in Emit("event name",(e)=>{}) will send the response to the server from client
             *
             *  Here event name in server and the script should be same
             */
            On("open", (Eventio) =>
            {
                Debug.Log("Connection made to the server");
            });
            On("register", (Eventio) =>
            {
                string id = Eventio.data["id"].ToString().RemoveQuotes();
                Debug.LogFormat("Our Client's Id ({0})", id);

                ClientID = id; // setting the Client id of the player
                Cliednt  = ClientID;
            });

            //This event will handle when the player spwan
            On("spawn", (Eventio) =>
            {
                string id = Eventio.data["id"].ToString().RemoveQuotes();

                GameObject go;
                go      = Instantiate(Swapingobject, Vector3.one, Quaternion.identity);
                go.name = "Service Id" + id;
                print("-=-=-=->" + go.name);
                NetworkIdentity ni = go.GetComponent <NetworkIdentity>();
                ni.SetControllerID(id);
                ni.SetSocketReference(this);
                go.transform.SetParent(networkContainer);
                serverObject.Add(id, go.GetComponent <NetworkIdentity>());
            });

            // This event will update the position of the Player
            On("updatepostion", (Eventio) =>
            {
                string id = Eventio.data["id"].ToString().RemoveQuotes();
                float x   = Eventio.data["position"]["x"].f;
                float y   = Eventio.data["position"]["y"].f;
                float z   = Eventio.data["position"]["z"].f;

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

            // This event will update the rotation of the player
            On("updaterotation", (Eventio) =>
            {
                string id            = Eventio.data["id"].ToString().RemoveQuotes();
                float tankRotation   = Eventio.data["tankRotation"].f;
                float barrelRotation = Eventio.data["barrelRotation"].f;

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

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

                if (!serverObject.ContainsKey(id))
                {
                    ServerObjectData Sod           = serverSpwanables.GetObjectByName(name);
                    var spawnobject                = Instantiate(Sod.Prefabs, networkContainer);
                    spawnobject.transform.position = new Vector3(x, y, 0);

                    var ni = spawnobject.GetComponent <NetworkIdentity>();
                    ni.SetControllerID(id);
                    ni.SetSocketReference(this);

                    serverObject.Add(id, ni);
                    // If Bullet applt direction as well
                    // print("-=-=Bullet-=-=->");
                    if (name == "Bullet")
                    {
                        float directionX = Eventio.data["Direction"]["x"].f;
                        float directionY = Eventio.data["Direction"]["y"].f;
                        float directionZ = Eventio.data["Direction"]["z"].f;
                        string activator = Eventio.data["activator"].str;
                        float speed      = Eventio.data["Speed"].f;

                        print("-=-=Bullet-=-=->");
                        float rot = Mathf.Atan2(directionY, directionX) * Mathf.Rad2Deg;
                        Vector3 currentRotation = new Vector3(0, 0, rot - 90);
                        print("currentRotation" + currentRotation + directionX);
                        spawnobject.transform.rotation = Quaternion.Euler(currentRotation);

                        WhoActivateMe whoActivateMe = spawnobject.transform.GetComponent <WhoActivateMe>();
                        whoActivateMe.SetActivator(activator);

                        Projectile projectile = spawnobject.GetComponent <Projectile>();
                        projectile.Direction  = new Vector3(directionX, directionY, directionZ);
                        projectile.Speed      = speed;
                    }
                }
            });

            On("serverUnSpawn", (Eventio) =>
            {
                string id          = Eventio.data["id"].ToString().RemoveQuotes();
                NetworkIdentity ni = serverObject[id];
                serverObject.Remove(id);
                DestroyImmediate(ni.gameObject);
            });

            On("playerDied", (Eventio) =>
            {
                print("-=-=PlayerDied-=-=->" + Eventio.data["id"].ToString());
                string id          = Eventio.data["id"].ToString().RemoveQuotes();
                NetworkIdentity ni = serverObject[id];

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

            On("playerRespawn", (Eventio) =>
            {
                string id          = Eventio.data["id"].ToString().RemoveQuotes();
                NetworkIdentity ni = serverObject[id];

                float x = Eventio.data["position"]["x"].f;
                float y = Eventio.data["position"]["y"].f;
                float z = Eventio.data["position"]["z"].f;

                ni.transform.position = new Vector3(x, y, z);
                ni.gameObject.SetActive(true);
            });

            On("disconnected", (Eventio) =>
            {
                print("-=-=-=-=->" + serverObject.Count);
                string id = Eventio.data["id"].ToString().RemoveQuotes();

                GameObject go = serverObject[id].gameObject;
                Destroy(go);
                serverObject.Remove(id);
                print("-=-=-=-=->" + serverObject.Count + " " + id);
            });
        }
Exemplo n.º 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 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);
                });
            });
        }
Exemplo n.º 7
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);
            });
        }
Exemplo n.º 8
0
        private void setupEvents()
        {
            On("open", (E) => {
                Debug.Log("Connection Made To The Server");
            });

            On("register", (E) => {
                ClientID = E.data["id"].ToString().Trim('"');

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

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

                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("disconected", (E) => {
                string id = E.data["id"].ToString().Trim('"');

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

            On("updatePosition", (E) => {
                string id = E.data["id"].ToString().Trim('"');
                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().Trim('"');
                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().Trim('"');
                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 spwanedObject                = Instantiate(sod.Prefab, networkContainer);
                    spwanedObject.transform.position = new Vector3(x, y, 0);
                    var ni = spwanedObject.GetComponent <NetworkIdentity>();
                    ni.SetControllerID(id);
                    ni.SetSocketReference(this);

                    //If bullet applay 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);
                        spwanedObject.transform.rotation = Quaternion.Euler(currentRotation);
                    }

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

            On("serverUnspawn", (E) => {
                string id          = E.data["id"].ToString().Trim('"');
                NetworkIdentity ni = serverObjects[id];
                serverObjects.Remove(id);
                DestroyImmediate(ni.gameObject);
            });
        }
Exemplo n.º 9
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);
            });
        }
Exemplo n.º 10
0
        private void SetupEvents()
        {
            On("open", (e) =>
            {
                Debug.Log("Connected to server");
            });

            On("register", (e) =>
            {
                ClientID = e.data["id"].ToString().RemoveQuotes();
                Debug.LogFormat("My client 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 ni = go.GetComponent <NetworkIdentity>();
                ni.SetCotrollerID(id);
                ni.SetSocketReference(this);
                serverObjects.Add(id, ni);

                //Enabling Camera
                if (ni.IsControlling())
                {
                    go.transform.Find("Third Person Camera").gameObject.SetActive(true);
                }
                Debug.LogFormat("I have spawned");
            });

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

                GameObject go = serverObjects[id].gameObject;
                Destroy(go);
                serverObjects.Remove(id);
                Debug.LogFormat("Disconnected");
            });

            On("updatePosition", (e) =>
            {
                string id = e.data["id"].ToString().RemoveQuotes();
                float x   = float.Parse(e.data["position"]["x"].str, CultureInfo.InvariantCulture.NumberFormat);
                float y   = float.Parse(e.data["position"]["y"].str, CultureInfo.InvariantCulture.NumberFormat);
                float z   = float.Parse(e.data["position"]["z"].str, CultureInfo.InvariantCulture.NumberFormat);

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

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

                float rotation = float.Parse(e.data["rotation"].str, CultureInfo.InvariantCulture.NumberFormat);

                NetworkIdentity ni            = serverObjects[id];
                ni.transform.localEulerAngles = new Vector3(0, rotation, 0);
            });

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

                float x = float.Parse(e.data["position"]["x"].str, CultureInfo.InvariantCulture.NumberFormat);
                float y = float.Parse(e.data["position"]["y"].str, CultureInfo.InvariantCulture.NumberFormat);
                float z = float.Parse(e.data["position"]["z"].str, CultureInfo.InvariantCulture.NumberFormat);

                float rotation = float.Parse(e.data["rotation"].str, CultureInfo.InvariantCulture.NumberFormat);

                NetworkIdentity ni = serverObjects[id];

                if (ni.gameObject.activeInHierarchy)
                {
                    StartCoroutine(AIPositionSmoothing(ni.transform, new Vector3(x, y, z)));
                    ni.GetComponent <EnemyManager>().SetRotation(rotation);
                }
            });

            On("serverSpawn", (e) =>
            {
                string name = e.data["name"].str;
                string id   = e.data["id"].ToString().RemoveQuotes();
                float x     = float.Parse(e.data["position"]["x"].ToString(), CultureInfo.InvariantCulture.NumberFormat);
                float y     = float.Parse(e.data["position"]["y"].ToString(), CultureInfo.InvariantCulture.NumberFormat);
                float z     = float.Parse(e.data["position"]["z"].ToString(), CultureInfo.InvariantCulture.NumberFormat);

                Debug.LogFormat("Server wants us to spawn a '{0}'", name);

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



                    //if bullet apply direction as well
                    //       if(name == "Bullet")
                    //        {
                    //            float directionX = float.Parse(e.data["direction"]["x"].str, CultureInfo.InvariantCulture.NumberFormat);
                    //            float directionY = float.Parse(e.data["direction"]["y"].str, CultureInfo.InvariantCulture.NumberFormat);
                    //            string activator = e.data["activator"].ToString().RemoveQuotes();
                    //            float speed = float.Parse(e.data["speed"].str, CultureInfo.InvariantCulture.NumberFormat);

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

                    //            WhoActivateMe whoActivateMe = spawnedObject.GetComponent<WhoActivateMe>();
                    //            whoActivateMe.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];
                ni.gameObject.SetActive(false);
            });



            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);   //I prefer use Invoke to make difference between Action and function
            });
        }
Exemplo n.º 11
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);
            });
        }