public void Connect(TcpClient _socket)
        {
            this.socket = _socket;
            this.socket.ReceiveBufferSize = dataBufferSize;
            this.socket.SendBufferSize    = dataBufferSize;

            this.stream = this.socket.GetStream();

            receivedData  = new Packet();
            recieveBuffer = new byte[dataBufferSize];

            this.stream.BeginRead(recieveBuffer, 0, dataBufferSize, recieveCallback, null);

            ServerSend.Welcome(id, "Bienvenido al servidor!");
        }
Exemple #2
0
 /// <summary>
 /// Calls the end of the round.
 /// </summary>
 /// <param name="team">Winner team.</param>
 public void EndRound(Player.Team team)
 {
     if (team == Player.Team.Murderer)
     {
         OnChangeRoundState(RoundState.END);
         ServerSend.RoundState((int)RoundState.END);
         ServerSend.RoundEnd((int)team);
     }
     else if (team == Player.Team.Bystander)
     {
         OnChangeRoundState(RoundState.END);
         ServerSend.RoundState((int)RoundState.END);
         ServerSend.RoundEnd((int)team);
     }
 }
 private static void TogglePvP(bool toggleValue)
 {
     if (toggleValue)
     {
         Log("PvP Enabled");
         ServerSettings.PvPEnabled = true;
         ServerSend.PvPEnabled();
     }
     else
     {
         Log("PvP Disabled");
         ServerSettings.PvPEnabled = false;
         ServerSend.PvPEnabled();
     }
 }
Exemple #4
0
        public static void StartNewGame()
        {
            currentRound = FIRST_ROUND;

            UpdateCurrentQuestion();

            foreach (ServerClient client in Server.Clients.Values)
            {
                client.Points = 0;
            }

            ServerSend.BroadcastNewGame(cardsNeededToWin, "[Server] Starting new game");

            StartNewRound(NO_WINNER, 8);
        }
Exemple #5
0
    private void Start()
    {
        id = nextEnemyId;
        nextEnemyId++;
        enemies.Add(id, this);
        health = maxHealth;

        ServerSend.SpawnEnemy(this);

        state = EnemyState.chaseStatue;
        agent = GetComponent <NavMeshAgent>();
        agent.updateUpAxis   = false;
        agent.updateRotation = false;
        rb2d.isKinematic     = true;
    }
Exemple #6
0
    public void Send()
    {
        string msg = msgInput.text;

        msgInput.text = string.Empty;
        if (NetworkManager.isServer())
        {
            PlaceMessage(0, msg);
            ServerSend.SendDebugMsg(0, msg);
        }
        if (NetworkManager.isClient())
        {
            ClientSend.SendDebugMsg(msg);
        }
    }
Exemple #7
0
    //==> SERVER
    #if SERVER
    //get notified when a new client joins the game
    public void InitClientScene(int _client, Action _onInitComplete)
    {
        Packet _packet = new Packet((int)ServerPackets.initScene);

        //ask all init components to prepare their data
        for (int i = 0; i < sceneInitComponents.Count; i++)
        {
            _packet.Write(sceneInitComponents[i].GetSubPacket().buffer.ToArray());
        }

        //save the response functionality
        sceneInitResponseFunctionality.Add(_client, _onInitComplete);
        //send the data over the network
        ServerSend.SendTCPData(_client, _packet);
    }
    private void Explode()
    {
        ServerSend.ProjectileExploded(this);

        Collider[] colliders = Physics.OverlapSphere(transform.position, explosionRadius);
        foreach (var collider in colliders)
        {
            if (collider.CompareTag("Player"))
            {
                collider.GetComponent <Player>().TakeDamage(explosionDamage);
            }
            projectiles.Remove(id);
            Destroy(gameObject);
        }
    }
    /// <summary>Disconnects the client and stops all network traffic.</summary>
    private void Disconnect()
    {
        Debug.Log($"{tcp.socket.Client.RemoteEndPoint} has disconnected.");

        ThreadManager.ExecuteOnMainThread(() =>
        {
            UnityEngine.Object.Destroy(player.gameObject);
            player = null;
        });

        tcp.Disconnect();
        udp.Disconnect();

        ServerSend.PlayerDisconnected(id);
    }
        /// <summary>Initializes the newly connected client's TCP-related info.</summary>
        /// <param name="_socket">The TcpClient instance of the newly connected client.</param>
        public void Connect(TcpClient _socket)
        {
            socket = _socket;
            socket.ReceiveBufferSize = dataBufferSize;
            socket.SendBufferSize    = dataBufferSize;

            stream = socket.GetStream();

            receivedData  = new Packet();
            receiveBuffer = new byte[dataBufferSize];

            stream.BeginRead(receiveBuffer, 0, dataBufferSize, ReceiveCallback, null);

            ServerSend.Welcome(id, "Welcome to the server!");
        }
Exemple #11
0
        /// <summary>Initializes the newly connected client's TCP-related info.</summary>
        /// <param name="clientSocket">The TcpClient instance of the newly connected client.</param>
        public void Connect(TcpClient clientSocket)
        {
            this.socket = clientSocket;
            this.socket.ReceiveBufferSize = DataBufferSize;
            this.socket.SendBufferSize    = DataBufferSize;

            stream = this.socket.GetStream();

            receivedData  = new Packet();
            receiveBuffer = new byte[DataBufferSize];

            stream.BeginRead(receiveBuffer, 0, DataBufferSize, ReceiveCallback, null);

            ServerSend.ServerConnection(id);
        }
Exemple #12
0
    public void AddFeature(GameObject go, bool buffer = true)
    {
        ChunkObject c = go.GetComponent <ChunkObject>(); //to get it to work, assign every ChunkObject prefab the script and add an id.

        c.myId  = objects.Count;
        c.chunk = this;
        objects.Add(nid, c);
        nid++;
        if (buffer)
        {
            ChunkMod result = new ChunkMod(ChunkMod.ChunkModType.Add, go.transform.position, c.myId, c.model);
            Server.bufferedChunkmods.Add(result);
            ServerSend.ChunkMod(result);
        }
    }
Exemple #13
0
    /// <summary>Processes player input and moves the player.</summary>
    public void FixedUpdate()
    {
        Vector2 _inputDirection = Vector2.zero;

        if (inputs[0])
        {
            _inputDirection.y += 1;
        }
        if (inputs[1])
        {
            _inputDirection.y -= 1;
        }
        if (inputs[2])
        {
            _inputDirection.x -= 1;
        }
        if (inputs[3])
        {
            _inputDirection.x += 1;
        }
        if (inputs[5])
        {
            WantToShoot();
        }
        if (inputs[6])
        {
            PickingUpPickables();
        }
        if (inputs[7])
        {
            StartCoroutine(Reload());
        }
        if (isGood == false)
        {
            if (health > 0)
            {
                health -= 3 * Time.fixedDeltaTime;
                ServerSend.PlayerHealth(this);
            }
            else
            {
                Died();
            }
        }

        Move(_inputDirection);
        ProgressStepCycle(moveSpeed, _inputDirection);
    }
Exemple #14
0
    //Invio Player ai Client
    public void SendIntoGame()
    {
        if (GameManager.instance.players.Count > Server.MaxPlayers)
        {
        }
        else
        {
            player = NetworkManager.instance.InstantiatePlayer();
            player.Initialize(id);
            // Send all players to the new player
            foreach (Client _client in Server.clients.Values)
            {
                if (_client.player != null)
                {
                    if (_client.id != id)
                    {
                        ServerSend.SpawnPlayer(id, _client.player);
                    }
                }
            }

            if (GameManager.instance.gameStarted)
            {
                player.ghost            = true;
                player.transform.tag    = "Ghost";
                player.gameObject.layer = LayerMask.NameToLayer("Ghost");
                ServerSend.SpawnGhost(id, player);
            }
            else
            {
                Debug.Log($"Spawning{id} ");
                // Send the new player to all players (including himself)
                foreach (Client _client in Server.clients.Values)
                {
                    if (_client.player != null)
                    {
                        ServerSend.SpawnPlayer(_client.id, player);
                    }
                }

                foreach (Gold_Spawner _spawner in GameManager.instance.golds.Values)
                {
                    ServerSend.SendGoldSpawner(id, _spawner.id);
                }
            }
            GameManager.instance.players.Add(id, player);
        }
    }
Exemple #15
0
 public static void pickupItem(int _fromClient, int id, int itemNumber)
 {
     if (GameManager.instance.gameItems[id] != null)
     {
         gameItem item = GameManager.instance.gameItems[id].GetComponentInChildren <gameItem>();
         if (item.pickup)
         {
             item.pickup = false;
             ServerSend.Item(id, itemNumber, _fromClient);
         }
     }
     else
     {
         ServerSend.RemoveItem(id);
     }
 }
Exemple #16
0
 public void TakeDamage(float _damage)
 {
     if (health <= 0)
     {
         return;
     }
     health -= _damage;
     if (health <= 0)
     {
         health             = 0f;
         transform.position = new Vector3(0f, 25f, 0f);
         ServerSend.PlayerPosition(this);
         StartCoroutine(Respawn());
     }
     ServerSend.PlayerHealth(this);
 }
Exemple #17
0
 /// <summary>Changes the selected weapon to the new one.</summary>
 /// <param name="_index">The index of the weapon to change in the inventory.</param>
 public void ChangeWeapon(int _index)
 {
     if (Inventory[_index] != null)
     {
         if (_index != selectedIndex)
         {
             ServerSend.PlayerChangeWeapon(GetComponent <Player>().id, _index);
             if (selectedIndex != -1)
             {
                 Inventory[selectedIndex].SetActive(false);
             }
             selectedIndex = _index;
             Inventory[selectedIndex].SetActive(true);
         }
     }
 }
Exemple #18
0
 public static void Reset()
 {
     Server.projectiles  = new Dictionary <int, Projectile>();
     Server.joinable     = true;
     ServerStart.started = false;
     Walls.Reset();
     BattleBus.Reset();
     ServerSend.Reset();
     foreach (ServerClient client in Server.clients.Values)
     {
         if (client.connected)
         {
             client.player = null;
         }
     }
 }
Exemple #19
0
    //handle the welcome message and character spawining
    public static void WelcomeReceived(int _fromClient, Packet _packet)
    {
        int    _clientIdCheck = _packet.ReadInt();
        string _username      = _packet.ReadString();

        Debug.Log($"{Server.clients[_fromClient].tcp.socket.Client.RemoteEndPoint} connected successfully and is now player {_fromClient}.");
        ServerStart.instance.DebugServer($"{Server.clients[_fromClient].tcp.socket.Client.RemoteEndPoint} connected successfully and is now player {_fromClient}.");
        if (_fromClient != _clientIdCheck)
        {
            Debug.Log($"Player \"{_username}\" (ID: {_fromClient}) has assumed the wrong client ID ({_clientIdCheck})!");
            ServerStart.instance.DebugServer($"Player \"{_username}\" (ID: {_fromClient}) has assumed the wrong client ID ({_clientIdCheck})!");
        }
        Server.clients[_fromClient].username  = _username;
        Server.clients[_fromClient].connected = true;
        ServerSend.SendUsernameList();
    }
    public void TakeDamage(float _damage)
    {
        if (health <= 0)
        {
            return;
        }

        health -= _damage;
        if (health <= 0)
        {
            health = 0f;
            Die();
        }

        ServerSend.PlayerHealth(this);
    }
        public void AddItem(InventoryItem aItem)
        {
            InventoryItem lIdenticalItem = items.Find((x) => x.Equals(aItem));

            if (lIdenticalItem != null)
            {
                lIdenticalItem.stack += aItem.stack;
            }
            else
            {
                items.Add(aItem);
            }

            ServerSend.InventoryItemAdded(parent, aItem);
            Debug.Log($"[Inventory] - Entity of type '{parent.Type}' with ID '{parent.ID}' has picked up {aItem.stack} instances of item with ID '{aItem.itemId}'.");
        }
Exemple #22
0
 public void SpawnPlayer(int playerId, int team)
 {
     foreach (var id in players.Values.Select(player => player.GetPlayerId()))
     {
         // Debug.Log($"Current BIG ID IS {id}");
         foreach (var oid in players.Values)
         {
             if (oid.GetPlayerId() == id)
             {
                 continue;
             }
             ServerSend.SpawnPlayer(id, oid.GetPlayerId(), currentPick[oid.GetPlayerId()], CurrentPlayerPositions[oid.GetPlayerId()]);
         }
         ServerSend.SpawnPlayer(id, id, currentPick[id], CurrentPlayerPositions[id]);
     }
 }
Exemple #23
0
    public void TakeDamage(float damage)
    {
        // Do not hurt again if dead already
        if (playerIsDead())
        {
            return;
        }

        health -= damage;
        if (playerIsDead())
        {
            Kill();
        }

        ServerSend.PlayerHealth(this);
    }
        public void Connect(TcpClient client)
        {
            socket = client;

            socket.ReceiveBufferSize = dataBufferSize;
            socket.SendBufferSize    = dataBufferSize;

            networkStream  = socket.GetStream();
            receiveBuffer  = new byte[dataBufferSize];
            receivedPacket = new Packet();

            networkStream.BeginRead(receiveBuffer, 0, dataBufferSize, new AsyncCallback(ReceiveCallback), null);

            // TODO: send welcome message to client! (done)
            ServerSend.Welcome(id, "Welcome to server!");
        }
Exemple #25
0
 public float TakeDamage(float amount, string _nameKiller, int weaponId)
 {
     if (health > 0)
     {
         health -= amount;
         ServerSend.PlayerHealth(this);
         ServerSend.PlayerSounds(transform.position, 8);
         return(health);
     }
     else
     {
         ServerSend.KillFeed(_nameKiller, username, weaponId);
         Died();
         return(health);
     }
 }
Exemple #26
0
 public void Shoot(Vector3 _camPosition, Vector3 _lookDir)
 {
     //TODO: Find a solution that requires less raycasts and feels less snappy
     if (Physics.Raycast(_camPosition, _lookDir, out RaycastHit _preHit, 100f))
     {
         Vector3 _shootDirection = (_preHit.point - shootOrigin.position).normalized;
         if (Physics.Raycast(shootOrigin.position, _shootDirection, out RaycastHit _hit, 100f))
         {
             if (_hit.collider.CompareTag("Player"))
             {
                 _hit.collider.GetComponent <Player>().TakeDamage(10f);
             }
             ServerSend.SpawnBullet(shootOrigin.position, _hit.point);
         }
         ServerSend.SpawnBullet(shootOrigin.position, _preHit.point);
     }
Exemple #27
0
    public void AddPlayer(Player player)
    {
        if (players.Count == maxPlayers)
        {
            return;
        }

        if (!players.Contains(player.dbid))
        {
            players.Add(player.dbid);
        }

        player.group = this;

        ServerSend.GroupMembers(groupId);
    }
Exemple #28
0
            public void Connect(TcpClient _socket)
            {
                socket = _socket;
                socket.ReceiveBufferSize = dataBufferSize;
                socket.SendBufferSize    = dataBufferSize;
                stream = socket.GetStream();
                //Khai báo package để giao tiếp client
                receivedData = new Packet();

                receiveBuffer         = new byte[dataBufferSize];
                receiveTransferBuffer = new byte[dataBufferSize];
                stream.BeginRead(receiveBuffer, 0, dataBufferSize, ReceiveCallback, null);
                //Gởi gói tin
                //ServerSend.Connect3(id, "CONNECT3");
                ServerSend.Welcome(id, "Welcome to the server!");
            }
Exemple #29
0
    /// <summary>Processes player input and moves the player.</summary>
    public void FixedUpdate()
    {
        if (interactTimeout > 0)
        {
            interactTimeout -= Time.deltaTime;
        }
        ChunkManagement();

        if (health <= 0f)
        {
            return;
        }

        Vector2 _inputDirection = Vector2.zero;

        if (inputs[0])
        {
            _inputDirection.y += 1;
        }
        if (inputs[1])
        {
            _inputDirection.y -= 1;
        }
        if (inputs[2])
        {
            _inputDirection.x -= 1;
        }
        if (inputs[3])
        {
            _inputDirection.x += 1;
        }
        cspeed = _inputDirection;
        if (seatIn == null)
        {
            state = PlayerStates.Walking;
            Move(_inputDirection);
        }
        else
        {
            state = PlayerStates.Sitting;
            seatIn.SetInputs(_inputDirection.y, _inputDirection.x);
            cspeed = -Vector3.one;
        }

        ServerSend.PlayerPosition(this);
        ServerSend.PlayerRotation(this);
    }
Exemple #30
0
    /// <summary>Calculates the player's desired movement direction and moves him.</summary>
    /// <param name="x"></param>
    /// <param name="z"></param>
    public void MoveTransform(float x, float z)
    {
        Vector3 _movementVector = Vector3.zero;
        Vector3 _currentInput   = Vector3.zero;

        _currentInput.x = x;
        _currentInput.z = z;

        normalizedInput = _currentInput.normalized;

        if ((Acceleration == 0) || (Deceleration == 0))
        {
            lerpedInput = _currentInput;
        }
        else
        {
            if (normalizedInput.magnitude == 0)
            {
                acceleration = Mathf.Lerp(acceleration, 0f, Deceleration * Time.deltaTime);
                lerpedInput  = Vector3.Lerp(lerpedInput, lerpedInput * acceleration, Time.deltaTime * Deceleration);
            }
            else
            {
                acceleration = Mathf.Lerp(acceleration, 1f, Acceleration * Time.deltaTime);
                lerpedInput  = Vector3.ClampMagnitude(normalizedInput, acceleration);
            }
        }

        _movementVector.x = lerpedInput.x;
        _movementVector.y = 0f;
        _movementVector.z = lerpedInput.z;

        movementSpeed = MovementSpeed * 1f;

        _movementVector *= movementSpeed;

        if (_movementVector.magnitude > MovementSpeed)
        {
            _movementVector = Vector3.ClampMagnitude(_movementVector, MovementSpeed);
        }

        Vector3 newMovement = rigidBody.position + _movementVector * Time.fixedDeltaTime;

        rigidBody.MovePosition(newMovement);

        ServerSend.PlayerPosition(this);
    }