示例#1
0
    public void JoinRoom(string room)
    {
        JsonData data = new JsonData();

        data.room = room;
        socket.Emit("joinRoom", JsonUtility.ToJson(data));
    }
示例#2
0
    void Start()
    {
        io.On("connect", (SocketIOEvent e) => {
            Debug.Log("SocketIO connected");
            io.Emit("test-event1");

            TestObject t = new TestObject();
            t.test       = 123;
            t.test2      = "test1";

            io.Emit("test-event2", JsonUtility.ToJson(t));

            TestObject t2 = new TestObject();
            t2.test       = 1234;
            t2.test2      = "test2";

            io.Emit("test-event3", JsonUtility.ToJson(t2), (string data) => {
                Debug.Log(data);
            });
        });

        io.Connect();

        io.On("test-event", (SocketIOEvent e) => {
            Debug.Log(e.data);
        });
    }
    public void CreateRoom()
    {
        Debug.Log("Create Room");

        RoomOptions roomOptions = new RoomOptions(2, 2, "Mi sala");

        socket.Emit("createRoom", JsonUtility.ToJson(roomOptions));
    }
示例#4
0
    // The backend calls this function to open a socket connection.
    // Once this happens, the game starts.
    public void EstablishConnection()
    {
        io.Connect();


        io.On("connect", (SocketIOEvent e) =>
        {
            Debug.Log("SocketIO Connected.");
        });


        io.On("world-init", (SocketIOEvent e) =>
        {
            Debug.Log("World init.");

            // So that the server knows that requests have started
            // being processed.
            io.Emit("client-ready", Convert.ToString(currentAvatarID));

            Debug.Log("Emitted response for the server for world initialisation.");
        });

        io.On("game-state", (SocketIOEvent e) =>
        {
            if (e.data == "")
            {
                return;
            }
            NewGameState(e.data);
        });
    }
示例#5
0
    public void Join()
    {
        Debug.Log("Join a room is clicked:" + EventSystem.current.currentSelectedGameObject.name);

        string roomName = GameObject.Find(EventSystem.current.currentSelectedGameObject.name).GetComponentInChildren <TextMeshProUGUI>().text;

        roomName = roomName.Split('\n')[0];

        SocketIOController io = GameObject.Find("SocketIOController").GetComponent <SocketIOController>();

        RoomName JSONobj = new RoomName();

        JSONobj.roomName = roomName;

        // socket io emit {join, room name}
        io.Emit("joinRoom", JsonUtility.ToJson(JSONobj), (string data) => {
            Debug.Log(data);
            bool roomAvailable = JsonUtility.FromJson <RoomAvailability>(data).roomAvailable;
            Debug.Log(roomAvailable);
            if (roomAvailable == true)
            {
                SceneManager.LoadScene("Arena-1", LoadSceneMode.Single);
            }
            else
            {
                GameObject notAvailableTextMeshInstance = Instantiate(notAvailableTextMesh, new Vector3(411, 470, 0), Quaternion.identity) as GameObject;
                // wait 1 second and delete message
                //Start the coroutine we define below named ExampleCoroutine.
                StartCoroutine(ExampleCoroutine(notAvailableTextMeshInstance));
            }
        });
    }
示例#6
0
    void Start()
    {
        Instance = this;
        io       = FindObjectOfType <SocketIOController>();

        io.On("connect", e =>
        {
            //We just connected to the socket server
            Debug.Log("Connected");
            io.Emit("vieweronline");
        });

        io.On("reset", e =>
        {
            SceneManager.LoadScene(0);
        });

        io.On("enroll", e =>
        {
            ScreenDetector.gameObject.SetActive(true);
            ScreenDetector.EnrollNewScreen(e);
        });

        io.Connect();
    }
示例#7
0
    public void SendName()
    {
        roomName = roomNameTextMesh.text;


        if (roomName != "")
        {
            SocketIOController io = GameObject.Find("SocketIOController").GetComponent <SocketIOController>();
            Debug.Log("room name received: " + roomName);
            RoomName JSONobj = new RoomName();
            JSONobj.roomName = roomName;
            Debug.Log("test:" + JSONobj.roomName + ":");
            // then send the name to the server
            io.Emit("createRoom", JsonUtility.ToJson(JSONobj), (string data) => {
                Debug.Log(data);
                bool roomAvailable = JsonUtility.FromJson <RoomAvailability>(data).roomAvailable;
                Debug.Log(roomAvailable);
                if (roomAvailable == true)
                {
                    SceneManager.LoadScene("Arena-1", LoadSceneMode.Single);
                }
                else
                {
                    notAvailableTextMesh.gameObject.SetActive(true);
                }
            });
        }
    }
示例#8
0
    // The backend calls this function to open a socket connection.
    // Once this happens, the game starts.
    public void EstablishConnection()
    {
        io.ResetSettings();

        io.On("connect", (SocketIOEvent e) =>
        {
            Debug.Log("SocketIO Connected.");
        });

        io.Connect();

        io.On("world-init", (SocketIOEvent e) =>
        {
            Debug.Log("World init.");

            // So that the server knows that requests have started
            // being processed.
            io.Emit("client-ready", Convert.ToString(userId));

            Debug.Log("Emitted response.");
        });

        io.On("world-update", (SocketIOEvent e) =>
        {
            WorldUpdate(e.data);
        });
    }
示例#9
0
    public void Log(string msg, string socketId = null)
    {
        if (socketId == null)
        {
            socketId = "";
        }

        string data = "{ \"msg\": " + JsonConvert.ToString(msg);

        if (!string.IsNullOrEmpty(socketId))
        {
            data += ", \"socketId\": \"" + socketId + "\"";
        }
        data += "}";
        Debug.Log("Socket Log: " + data);
        io.Emit("log", data);
    }
示例#10
0
 //Method to send back current position from this player (and all others) to currently spawning player
 private void OnRequestPosition(SocketIOEvent e)
 {
     //Debug.Log ("Another player requested position " + e.data);
     //Debug.Log ("My current position " + LocationToJson(myPlayer.transform.position));
     //Will update my position on spawning player's screen
     //TODO: Add direction to this
     socket.Emit("updatePosition", LocationToJson(myPlayer.transform.position));
 }
示例#11
0
    void Start()
    {
        //Server cost: https://glitch.com/edit/#!/relay-server
        //Web client: https://relay-server.glitch.me/
        //
        // Server Commands
        // -Client to Server
        // 💬join (roomKey)
        // 💬leave (roomKey)
        // 💬whoami ()
        // 💬whoslistening ()
        //
        // -Server to Client
        // 💬youare (socketKey)
        // 💬joined
        // 💬peerjoin (socketKey)
        // 💬peerdrop (socketKey)
        // 💬listeners ([{ room: "theRoomKey", sockets: ["123", ...] }, ...])


        //On Connected Event
        io.On("connect", e =>
        {
            Debug.Log("Socket connected");
            io.Emit("💬join", "\"exampleRoom\"");
        });

        //Event notification when this client joins a room on the relay
        io.On("💬joined", e =>
        {
            Debug.Log("Joined room: " + e.data);

            //Broadcast a message for relay
            io.Emit("appSpecificMessage", "\"Hello from Unity\""); //Note the enclosing double quotes. IO is actually expecting JSON values, so strings need to be quoted
        });

        //Event notification when we receive an app specific message
        io.On("appSpecificMessage", e =>
        {
            Debug.Log("Received appSpecificMessage: " + e.data);
        });

        //Actually initiate the connection to the server
        io.Connect();
    }
示例#12
0
    void HandleConnect(SocketIOEvent e)
    {
        Debug.Log("SocketIO connected");
        if (string.IsNullOrEmpty(GameManager.instance.LocalPlayerId))
        {
        #if UNITY_EDITOR || UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX
            io.Emit("getmockidentity");
            GameManager.instance.OnAllPlayersReady();
        #endif

        #if UNITY_WEBGL
            io.Emit("getidentity");
        #endif
        }
    }
    void Start()
    {
        sprite = GetComponent <SpriteRenderer>();


        io.On("connect", (SocketIOEvent e) => {
            Debug.Log("SocketIO connected");
            io.Emit("test-event1");

            TestObject t = new TestObject();
            t.test       = 123;
            t.test2      = "test1";

            io.Emit("test-event2", JsonUtility.ToJson(t));

            TestObject t2 = new TestObject();
            t2.test       = 1234;
            t2.test2      = "test2";

            io.Emit("test-event3", JsonUtility.ToJson(t2), (string data) => {
                Debug.Log(data);
            });
        });

        io.Connect();

        io.On("test-event", (SocketIOEvent e) => {
            Debug.Log(e.data);
            sprite.color = Color.blue;
        });

        io.On("register", (SocketIOEvent e) => {
            Debug.Log("CORA");
        });

        /*
         * io.On("keyword", (SocketIOEvent e) => {
         * Debug.Log("registered");
         * });
         */
    }
示例#14
0
 private void OnTriggerStay2D(Collider2D other)
 {
     if (isLeft)
     {
         if (scriptPlayerController.isAttackingLeft())
         {
             if (other.gameObject.tag == "Player")
             {
                 Debug.Log("Other character died on left");
                 Destroy(other.gameObject);
                 // TODO: io send playerDeath
                 string       playerName = other.gameObject.name;
                 string       playerId   = playerName.Remove(0, 6); //Player
                 PlayerIdJSON obj        = new PlayerIdJSON();
                 obj.playerId = playerId;
                 io.Emit("playerKilled", JsonUtility.ToJson(obj));
             }
         }
     }
     else
     {
         if (scriptPlayerController.isAttackingRight())
         {
             if (other.gameObject.tag == "Player")
             {
                 Debug.Log("Other character died on right");
                 Destroy(other.gameObject);
                 // TODO: io send playerDeath
                 Destroy(other.gameObject);
                 // TODO: io send playerDeath
                 string       playerName = other.gameObject.name;
                 string       playerId   = playerName.Remove(0, 6); //Player
                 PlayerIdJSON obj        = new PlayerIdJSON();
                 obj.playerId = playerId;
                 io.Emit("playerKilled", JsonUtility.ToJson(obj));
             }
         }
     }
 }
    void Update()
    {
        if (totalEnergy < neededEnergy || collectedEnergy >= neededEnergy)
        {
            if (!disconnected)
            {
                socket.Emit("gameover");
                socket.Close();

                disconnected = true;
            }

            //print ("Game Over!");
            anim.SetTrigger("IsGameOver");

            restartTimer += Time.deltaTime;

            if (restartTimer >= restartDelay)
            {
                Application.LoadLevel(Application.loadedLevel);
            }
        }
    }
    private void EmitNewPostion()
    {
        if (Time.time - lastEmitTime > timeToEmit)
        {
            lastEmitTime = Time.time;

            var currentMovement = new EnemyMovement(sessionId, enemy.position.x, enemy.position.z, enemy.rotation.eulerAngles.y);

            if (!currentMovement.Equals(lastMovement))
            {
                lastMovement = currentMovement;

                socket.Emit("enemy", currentMovement.ToString());
            }
        }
    }
示例#17
0
    public void RefreshRoomsList()
    {
        Debug.Log("refresh room list");
        SocketIOController io = GameObject.Find("SocketIOController").GetComponent <SocketIOController>();

        io.Emit("refreshRoomsList", JsonUtility.ToJson(""), (string data) => {
            Debug.Log(data);
            RoomsList roomsList = new RoomsList();
            roomsList           = JsonUtility.FromJson <RoomsList>(data);
            foreach (Room room in roomsList.Rooms)
            {
                Debug.Log(room.roomName);
                GameObject buttonPrefabInstance = Instantiate(buttonPrefab, content.transform, false) as GameObject;
                buttonPrefabInstance.name       = "Button" + room.roomName;
                //buttonPrefabInstance.transform.parent = content.transform;
                buttonPrefabInstance.GetComponentInChildren <TextMeshProUGUI>().text = room.roomName + "\nnumber of players: " + room.numPlayers.ToString() + "/4";
            }
        });
    }
        void FixedUpdate()
        {
            float lh = Input.GetAxisRaw("Horizontal");
            float lv = Input.GetAxisRaw("Vertical");

            if (socket != null && playerRigidBody != null)
            {
                var currentMovement =
                    new PlayerMovement(sessionId, playerRigidBody.position.x, playerRigidBody.position.z, playerRigidBody.rotation.eulerAngles.y, lh != 0f || lv != 0, lh, lv);

                if (!currentMovement.MovementIsEqual(lastMovement))
                {
                    lastMovement = currentMovement;
                    socket.Emit("move", currentMovement.ToString());
                }
            }

            characterMovement.Move(lh, lv);
        }
 public void AttemptToJoinLobby()
 {
     io.Emit("joinGame");
 }
示例#20
0
        // Import the JSLib as following. Make sure the
        // names match with the JSLib file we've just created.

        private void setupEvents()
        {
            io.On("connect", (e) => {
                io.Emit("addUnityUser");
            });

            io.On("register", (e) => {
                Player player = JsonUtility.FromJson <Player>(e.data);
                ClientId      = player.id;
                Debug.LogFormat("pur client Id", ClientId);
            });

            io.On("spawn", (SocketIOEvent e) => {
                Player newPlayer   = JsonUtility.FromJson <Player>(e.data);
                GameObject go      = Instantiate(playerPrefab, networkContainer);
                go.name            = string.Format("Player ({0})", newPlayer.id);
                NetworkIdentity ni = go.GetComponent <NetworkIdentity>();
                ni.SetControllerId(newPlayer.id);
                ni.SetSocketRefrence(io);
                serverObjects.Add(newPlayer.id, ni);
            });

            io.On("updatePosition", (e) => {
                Player player         = JsonUtility.FromJson <Player>(e.data);
                string id             = player.id;
                float x               = player.position.x;
                float y               = player.position.y;
                NetworkIdentity ni    = serverObjects[id];
                ni.transform.position = new Vector3(x, y, 0);
            });

            // gets called if someone is playing on a difrent tab or browser
            io.On("duplicatePlayer", (e) => {
                Debug.Log("UNITY : duplicatePlayer");
                io.Close();
                SceneManager.LoadScene("test");
            });

            // gets called if someone signout of the react client
            io.On("disconnectFromReact", (e) => {
                Debug.Log("UNITY : disconnectFromReact");
                Player player = JsonUtility.FromJson <Player>(e.data);
                Debug.Log(player);
                string id     = player.id;
                GameObject go = serverObjects[id].gameObject;
                Destroy(go);
                serverObjects.Remove(id);
            });

            //gets called if someonecloses a tab
            io.On("disconnected", (e) => {
                Debug.Log("UNITY : disconnect");
                Player player = JsonUtility.FromJson <Player>(e.data);
                Debug.Log(e.data);
                string id = player.id;

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

            io.Connect();
        }
示例#21
0
        protected void Update()
        {
            if (GetComponent <LocalPlayer>().isLocalPlayer)
            {
                if (Input.GetMouseButtonDown(0))
                {
                    anim.SetTrigger("Attack");
                    GetComponent <PlayerState>().isAttacking = true;

                    // TODO: io send attack
                    io.Emit("attack");
                }

                targetedVelocity = Vector2.zero;

                moveInput = Input.GetAxisRaw("Horizontal");



                if (moveInput < 0)
                {
                    targetedVelocity.x = -1 * maxSpeed;
                    GetComponent <PlayerState>().isLookingToRight = false;
                    eulerAngles.y         = -120;
                    transform.eulerAngles = eulerAngles;
                }
                else if (moveInput > 0)
                {
                    targetedVelocity.x = maxSpeed;
                    GetComponent <PlayerState>().isLookingToRight = true;
                    eulerAngles.y         = 120;
                    transform.eulerAngles = eulerAngles;
                }

                if (Input.GetButtonDown("Jump"))
                {
                    jump = true;
                    Debug.Log("Need to jump");

                    io.Emit("jump");
                }


                ComputeVelocity(targetedVelocity);

                if (GetComponent <LocalPlayer>().isLocalPlayer)
                {
                    if (targetedVelocity != oldVelocity)
                    {
                        io.Emit("velocityChanged", JsonUtility.ToJson(targetedVelocity));
                        oldVelocity = targetedVelocity;
                    }

                    // sharing position if the position changed
                    if (Vector3.Distance(transform.position, oldPosition) > 0.02f)
                    {
                        Debug.Log(Vector3.Distance(transform.position, oldPosition));
                        io.Emit("playerMoved", JsonUtility.ToJson(transform.position));
                        oldPosition = transform.position;
                    }

                    if (transform.eulerAngles != oldEulerAngle)
                    {
                        Debug.Log("Player rotated");
                        io.Emit("playerRotated", JsonUtility.ToJson(transform.eulerAngles));
                        oldEulerAngle = transform.eulerAngles;
                    }
                }
            }
        }
示例#22
0
 //Move the Character for other people
 public void SendMove(float x, float y)
 {
     //Debug.Log("sending position to node: " + Network.DirectionsToJson(x,y));
     //Send position to server
     socket.Emit("move", Network.DirectionsToJson(x, y));
 }
示例#23
0
    void OnApplicationQuit()
    {
        DisconnectedPacket packet = new DisconnectedPacket();

        packet.id = localID;

        socket.Emit("disconnected", JsonUtility.ToJson(packet));
    }
 private void onConnect(SocketIOEvent e)
 {
     Debug.Log("Socket connected");
     io.Emit("💬join", quote(RoomName));
     io.Emit("💬whoami");
 }
示例#25
0
 public void SendCheatCode()
 {
     socket.Emit("cheatcode");
 }
示例#26
0
    void Start()
    {
        io = GameObject.Find("SocketIOController").GetComponent <SocketIOController>();
        io.On("connect", (SocketIOEvent e) => {
            Debug.Log("SocketIO connected");



            io.Emit("test-event1");

            TestObject t = new TestObject();
            t.test       = 123;
            t.test2      = "test1";

            io.Emit("test-event2", JsonUtility.ToJson(t));

            TestObject t2 = new TestObject();
            t2.test       = 1234;
            t2.test2      = "test2";

            io.Emit("test-event3", JsonUtility.ToJson(t2), (string data) => {
                Debug.Log(data);
            });
        });

        io.On("allPlayersPositions", (SocketIOEvent ev) => {
            Debug.Log("allPlayersPositions received");
            Debug.Log(ev.data.ToString());
            PlayersList playersList = new PlayersList();
            playersList             = JsonUtility.FromJson <PlayersList>(ev.data);
            foreach (Players player in playersList.Players)
            {
                Debug.Log(player.playerId);
                Debug.Log(player.pos);
                string playerName         = "Player" + player.playerId;
                GameObject playerInstance = Instantiate(playerPrefab, player.pos, Quaternion.identity);
                playerInstance.name       = playerName;
                playerInstance.tag        = "Player";

                /*LocalPlayer localPlayer = playerInstance.GetComponent<LocalPlayer>();
                 * localPlayer.playerId = player.playerId;
                 */
            }
        });

        // delete an instance of the disconnected player
        io.On("playerDisconnected", (SocketIOEvent ev) => {
            string playerId   = JsonUtility.FromJson <PlayerIdJSON>(ev.data).playerId;
            string playerName = "Player" + playerId;
            Destroy(GameObject.Find(playerName));
        });

        io.On("spawnPlayer", (SocketIOEvent ev) => {
            playerSpawn.GetComponent <SpawnPlayer>().spawnLocalPlayer();
        });

        io.On("moveInput", (SocketIOEvent ev) => {
            Debug.Log("moveInput received : " + ev.data.ToString());
            Movement movement = JsonUtility.FromJson <Movement>(ev.data);
            string playerName = "Player" + movement.playerId;
            GameObject.Find(playerName).GetComponent <PlayerState>().moveInput = movement.moveInput;
        });

        io.On("playerMoved", (SocketIOEvent ev) => {
            Debug.Log("playerMoved received : " + ev.data.ToString());
            PlayerPos playerPos = JsonUtility.FromJson <PlayerPos>(ev.data);
            string playerId     = playerPos.playerId;
            string playerName   = "Player" + playerId;
            Debug.Log(playerName);
            GameObject playerToMove = GameObject.Find(playerName);

            if (playerToMove == null)
            {
                playerToMove      = Instantiate(playerPrefab, playerPos.pos, Quaternion.identity);
                playerToMove.name = playerName;
                playerToMove.tag  = "Player";
                playerToMove.GetComponent <LocalPlayer>().setPlayerId(playerId);
            }

            // TODO: playerToMove.Move(player.pos);

            playerToMove.transform.position = playerPos.pos;
            Debug.Log("playerPos.pos");
            Debug.Log(playerPos.pos);

            /*if(playerToMove != null){
             *  playerToMove.transform.position = playerPos.pos;
             * }
             * else{
             *  Debug.Log("cannot find the playerToMove!");
             * }*/
        });

        io.On("playerRotated", (SocketIOEvent ev) => {
            Debug.Log("playerRotated received : " + ev.data.ToString());
            PlayerPos playerPos = JsonUtility.FromJson <PlayerPos>(ev.data);
            string playerId     = playerPos.playerId;
            string playerName   = "Player" + playerId;
            Debug.Log(playerName);
            GameObject playerToMove = GameObject.Find(playerName);

            playerToMove.transform.eulerAngles = playerPos.pos;
            Debug.Log("playerPos.pos");
            Debug.Log(playerPos.pos);
        });

        io.On("velocityChanged", (SocketIOEvent ev) => {
            Debug.Log("velocityChanged received : " + ev.data.ToString());
            PlayerVelocity playerVelocity = JsonUtility.FromJson <PlayerVelocity>(ev.data);
            string playerId   = playerVelocity.playerId;
            string playerName = "Player" + playerId;
            Debug.Log(playerName);
            GameObject playerToMove = GameObject.Find(playerName);

            playerToMove.GetComponent <PlayerController>().ComputeVelocity(playerVelocity.velocity);

            /*if (playerVelocity.velocity.x == 0)
             * {
             *  playerToMove.GetComponent<Animator>.SetBool("IsRunning", false);
             * }
             * else
             * {
             *  playerToMove.GetComponent<Animator>.SetBool("IsRunning", true);
             * }*/
            Debug.Log("playerVelocity.velocity");
            Debug.Log(playerVelocity.velocity);
        });



        io.On("playerAttack", (SocketIOEvent ev) => {
            Debug.Log("playerAttack received");
            string playerId           = JsonUtility.FromJson <PlayerIdJSON>(ev.data).playerId;
            string playerName         = "Player" + playerId;
            GameObject playerInstance = GameObject.Find(playerName);
            playerInstance.GetComponent <PlayerState>().isAttacking = true;
            playerInstance.GetComponent <Animator>().SetTrigger("Attack");
        });

        io.On("playerEndAttack", (SocketIOEvent ev) => {
            Debug.Log("playerAttack received");
            string playerId   = JsonUtility.FromJson <PlayerIdJSON>(ev.data).playerId;
            string playerName = "Player" + playerId;
            GameObject.Find(playerName).GetComponent <PlayerState>().isAttacking = false;
        });

        io.On("jump", (SocketIOEvent ev) => {
            Debug.Log("jump received");
            string playerId   = JsonUtility.FromJson <PlayerIdJSON>(ev.data).playerId;
            string playerName = "Player" + playerId;
            GameObject.Find(playerName).GetComponent <PlayerState>().jump = true;
        });


        io.On("playerKilled", (SocketIOEvent ev) => {
            Debug.Log("another player killed by a player");
            string playerId   = JsonUtility.FromJson <PlayerIdJSON>(ev.data).playerId;
            string playerName = "Player" + playerId;
            Destroy(GameObject.Find(playerName));
        });

        io.On("playerDeathByDeathFloor", (SocketIOEvent ev) => {
            Debug.Log("another player killed by death floor");
            string playerId   = JsonUtility.FromJson <PlayerIdJSON>(ev.data).playerId;
            string playerName = "Player" + playerId;
            Destroy(GameObject.Find(playerName));
        });

        /*io.On("anotherPlayerConnected", (SocketIOEvent e) => {
         *  Debug.Log(e.data);
         *  Instantiate(myPrefab, new Vector3(0, 0, 0), Quaternion.identity);
         * });*/

        io.Connect();

        io.On("test-event", (SocketIOEvent e) => {
            Debug.Log(e.data);
        });
    }
 //send data for validation
 public void SendAvatarData(AvatarData aData)
 {
     if(socket != null)
        socket.Emit("avatarData", JsonUtility.ToJson(aData));
 }
示例#28
0
 public void requestPlayersPosition()
 {
     io.Emit("requestPlayersPos");
 }
示例#29
0
 public virtual void StartNewGame(Action <string> onGameCreated)
 {
     socket.Emit("newgame", onGameCreated);
 }