Exemplo n.º 1
0
    static void switchPlayer(NetworkMessage netMsg)
    {
        canSwitchCameraView = true;

        var msg = netMsg.ReadMessage <MyMessage>();

        if (currentPlayer != null)
        {
            currentMovingPlayer.enabled = false;
            currentPlayer.transform.Find("UIoverlay").gameObject.SetActive(false);
            //hide that player's UI frame
        }

        GameObject go = ClientScene.FindLocalObject(msg.netId);

        currentPlayer               = go.GetComponent <Player>();
        currentMovingPlayer         = go.GetComponent <MovingPlayer>();
        currObservedPlayerId        = currentPlayer.netId;
        currentMovingPlayer.enabled = true;
        Transform uioverlay = currentPlayer.transform.Find("UIoverlay");

        uioverlay.gameObject.SetActive(true);
    }
Exemplo n.º 2
0
    void RpcSpawnItemThirdPerson(NetworkInstanceId itemModelNetId, NetworkInstanceId itemShadowNetId)      // Sets parent of third person item and sets it to proper visibility layer
    {
        currentItemThirdPerson        = ClientScene.FindLocalObject(itemModelNetId);
        currentItemThirdPersonShadows = ClientScene.FindLocalObject(itemShadowNetId);

        currentItemThirdPerson.transform.SetParent(thirdPersonRightHand.transform);
        currentItemThirdPersonShadows.transform.SetParent(thirdPersonRightHand.transform);

        if (isLocalPlayer)
        {
            foreach (Transform child in currentItemThirdPerson.GetComponentsInChildren <Transform>())
            {
                child.gameObject.layer = 8;
            }
            foreach (Transform child in currentItemThirdPersonShadows.GetComponentsInChildren <Transform>())
            {
                if (child.GetComponent <Renderer> ())
                {
                    child.GetComponent <Renderer> ().shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.ShadowsOnly;
                }
            }
        }
    }
Exemplo n.º 3
0
    void CmdTileInteract(NetworkInstanceId tileID)
    {
        Tile tile = ClientScene.FindLocalObject(tileID).GetComponent <Tile>();

        if (tile.units.Count > 0)
        {
            //Add unit to squad, remove from tile
            if (tile.units[0].Follower.rooted != true)
            {
                CmdAddUnitToSquad(tile.units[0]);
                tile.units.Remove(tile.units[0]);
            }
        }
        else
        {
            //Remove unit from squad, add to tile
            if (squad.Count > 0)
            {
                tile.CmdAddUnit(squad[0]);
                CmdRemoveUnitFromSquad(squad[0]);
            }
        }
    }
    public void CmdDamage(
        NetworkInstanceId attackerID, NetworkInstanceId targetID, float damage)
    {
        var attackerIdentity = ClientScene.FindLocalObject(attackerID).GetComponent <NetworkIdentity>();
        var targetIdentity   = ClientScene.FindLocalObject(targetID).GetComponent <NetworkIdentity>();
        var targetHealth     = targetIdentity.GetComponent <Health>();
        //Debug.Log(attackerIdentity);
        //Debug.Log(targetIdentity);
        //Debug.Log(targetHealth);
        var targetConnection = targetIdentity.connectionToClient;

        if (targetConnection == null)
        {
            targetHealth.takeDamage(damage);
        }
        else
        {
            targetHealth.TargetTakeDamage(targetIdentity.connectionToClient, damage);
        }
        //Debug.Log(targetIdentity.connectionToClient);
        //if(targetIdentity.player)
        //ask the target if the damage can be processed
    }
Exemplo n.º 5
0
        public void LoadUnloadAmmo(NetworkInstanceId magazineID)
        {
            //if the magazine ID is invalid remove the magazine
            if (magazineID == NetworkInstanceId.Invalid)
            {
                CurrentMagazine = null;
            }
            else
            {
                //find the magazine by NetworkID
                GameObject magazine = ClientScene.FindLocalObject(magazineID);
                if (magazine != null)
                {
                    MagazineBehaviour magazineBehavior = magazine.GetComponent <MagazineBehaviour>();
                    CurrentMagazine = magazineBehavior;
//					Debug.LogFormat("MagazineBehaviour found ok: {0}", magazineID);
                }
                else
                {
//					Debug.Log("Could not find MagazineBehaviour");
                }
            }
        }
Exemplo n.º 6
0
    public void AddPlayerasDriver(NetworkInstanceId parent)
    {
        GameObject tank = ClientScene.FindLocalObject(parent);

        transform.parent = tank.transform.GetChild(0);
        Transform turretSpawnPos = tank.transform.GetChild(0).GetChild(12);
        Transform driverSpawnPos = tank.transform.GetChild(0).GetChild(13);

        Hand1 = transform.GetChild(0).gameObject;
        Hand2 = transform.GetChild(1).gameObject;
        //Hand1.transform.parent = transform.parent;
        //Hand2.transform.parent = transform.parent;

        if (isLocalPlayer)
        {
            MainCamera = GameObject.Find("Main Camera (origin)");
            MainCamera.transform.parent   = tank.transform.GetChild(0);
            MainCamera.transform.position = driverSpawnPos.position;
            MainCamera.transform.rotation = driverSpawnPos.rotation;
            controller1 = MainCamera.transform.GetChild(2).GetChild(1).gameObject;
            controller2 = MainCamera.transform.GetChild(3).GetChild(1).gameObject;
        }
    }
Exemplo n.º 7
0
    public override void OnStartClient()
    {
        if (parentNetId.IsEmpty())
        {
            return;
        }

        GameObject parentObject = ClientScene.FindLocalObject(parentNetId);

        Transform parent = parentObject.transform;

        if (parentObject.GetComponent <ItemManager>())
        {
            parent = parentObject.GetComponent <ItemManager>().hand;
        }

        // Set parent and position
        transform.SetParent(parent);
        transform.localPosition = Vector3.zero;
        transform.localRotation = Quaternion.identity;

        DisablePhysics();
    }
Exemplo n.º 8
0
    public void SetFriendHud(PlayerList someConnectedPlayers)
    {
        if (!isLocalPlayer)
        {
            return;
        }

        myFriendList.Clear();
        foreach (Transform child in myFriendList.gameObject.transform)
        {
            CmdUnsubscribe(child.gameObject);
            Destroy(child.gameObject);
        }


        for (int index = 0; index < someConnectedPlayers.Count; index++)
        {
            if (someConnectedPlayers[index].netId == myCharacter.GetComponent <NetworkIdentity>().netId)
            {
                continue;
            }

            GameObject player = ClientScene.FindLocalObject(someConnectedPlayers[index].netId);

            GameObject friend = Instantiate(myFriendList.myFriendlistHudPrefab, myFriendList.transform);
            friend.GetComponent <FriendHud>().SetCharacter(player);
            friend.GetComponent <FriendHud>().SetParent(myCharacter.GetComponent <PlayerCharacter>());

            PlayerCharacter playerCharacter = player.GetComponent <PlayerCharacter>();
            CharacterHUD    hud             = friend.GetComponent <CharacterHUD>();
            hud.SetName(playerCharacter.Name);
            hud.SetHealthBarFillAmount(player.GetComponent <Health>().GetHealthPercentage());
            myFriendList.AddHud(hud, someConnectedPlayers[index].netId, myCharacter.GetComponent <PlayerCharacter>().Name);

            CmdSubscribe(player);
        }
    }
Exemplo n.º 9
0
        public static void Postfix(NetworkMessage msg)
        {
            msg.reader.SeekZero();
            RespawnMessage respawnMessage = msg.ReadMessage <RespawnMessage>();

            GameObject gameObject = ClientScene.FindLocalObject(respawnMessage.m_net_id);

            if (gameObject == null)
            {
                return;
            }
            Player playerFromNetId = gameObject.GetComponent <Player>();

            if (playerFromNetId == null)
            {
                return;
            }

            if (playerFromNetId.isLocalPlayer)
            {
                if (MenuManager.opt_primary_autoswitch == 0 && MPAutoSelection.primarySwapFlag)
                {
                    if (GameplayManager.IsMultiplayerActive && NetworkMatch.InGameplay())
                    {
                        MPAutoSelection.maybeSwapPrimary(true);
                    }
                }

                if (MPAutoSelection.secondarySwapFlag)
                {
                    if (GameplayManager.IsMultiplayerActive && NetworkMatch.InGameplay())
                    {
                        MPAutoSelection.maybeSwapMissiles(true);
                    }
                }
            }
        }
Exemplo n.º 10
0
    /// <summary>
    /// Invoked on all clients and server when the server updates MagNetID, updating the local version of this weapon to
    /// load / unload the mag.
    /// </summary>
    /// <param name="magazineID">id of the new magazine to load, NetworkInstanceId.Invalid if we should unload
    /// the current mag</param>
    private void OnMagNetIDChanged(NetworkInstanceId magazineID)
    {
        //if the magazine ID is invalid remove the magazine
        if (magazineID == NetworkInstanceId.Invalid)
        {
            CurrentMagazine = null;
        }
        else
        {
            if (CurrentMagazine != null)
            {
                Logger.LogError("Attempted to load a new mag while a " +
                                "mag is still in the weapon in our local instance of the game. " +
                                "This is probably a bug. Continuing anyway...");
            }
            //find the magazine by NetworkID
            GameObject magazine = ClientScene.FindLocalObject(magazineID);
            if (magazine != null)
            {
                MagazineBehaviour magazineBehavior = magazine.GetComponent <MagazineBehaviour>();
                CurrentMagazine = magazineBehavior;
                var cnt = magazine.GetComponent <CustomNetTransform>();
                if (isServer)
                {
                    cnt.DisappearFromWorldServer();
                }
                else
                {
                    cnt.DisappearFromWorld();
                }

                Logger.LogTraceFormat("MagazineBehaviour found ok: {0}", Category.Firearms, magazineID);
                //sync ammo count now that we will potentially be shooting this locally.
                SyncMagAmmoAndRNG();
            }
        }
    }
Exemplo n.º 11
0
    //Whenever ship collides with an interactable object
    void OnCollisionEnter(Collision collision)
    {
        InteractiveObject interaction = collision.transform.GetComponent <InteractiveObject>();

        if (interaction == null)
        {
            return;
        }

        //allow the interaction only if the object isn't owned by player it is touching
        if (interaction.owner != GetComponent <NetworkIdentity>().netId)
        {
            GameObject otherPlayerBoat = ClientScene.FindLocalObject(interaction.owner);

            StatusEffectsManager ourEffectsManager = GetComponent <StatusEffectsManager>();

            int teamOfObject = otherPlayerBoat == null ? -1 : otherPlayerBoat.GetComponent <Health>().team;

            //allow the interaction only if the object touching us is owned by an enemy and the object is allowed to interact with enemies
            //or if the object touching us is owned by a teammate and the object is allowed to interact with teammates
            //or if the interaction object isn't owned by any particular player
            if (teamOfObject == -1 || (teamOfObject == team && interaction.DoesEffectTeammates()) || (teamOfObject != team && interaction.DoesEffectEnemies()))
            {
                //tell the interactive object about the interaction
                //giving them this health, the boat this health is attached to, this boats status effect manager, and the collision that caused the interaction
                //if(isServer)
                interaction.OnInteractWithPlayer(this, gameObject, ourEffectsManager, collision);

                //if we are the server, destroy the interactive object after the interaction
                //if it says it is destroy after interactions
                if (interaction.DoesDestroyInInteract())
                {
                    Destroy(collision.gameObject);
                }
            }
        }
    }
Exemplo n.º 12
0
    void RpcHitReaction(NetworkInstanceId netId, Vector3 point, Vector3 normal, NetworkInstanceId attackerid, Hitpart part)
    {
        GameObject hit      = ClientScene.FindLocalObject(netId);
        GameObject attacker = ClientScene.FindLocalObject(attackerid);

        if (hit != null && attacker != null)
        {
            if (hit.GetComponent <Rigidbody>() != null)
            {
                hit.GetComponent <Rigidbody>().AddForce(fpsCamera.transform.forward * 200f);
            }
            BulletSound bs = hit.GetComponent <BulletSound>();
            if (bs != null)
            {
                bs.Play();
            }
            BulletRandomSound brs = hit.GetComponent <BulletRandomSound>();
            if (brs != null)
            {
                brs.Play();
            }

            Hitreaction hr = hit.GetComponent <Hitreaction>();
            if (hr != null)
            {
                MobController mc = hit.GetComponent <MobController>();
                if (mc != null)
                {
                    mc.attacker = attacker;
                }
                hr.React(part.ToString());
            }

            MakeImpactFX(point, normal);
            MakeBulletHole(point, normal, hit.transform);
        }
    }
Exemplo n.º 13
0
    public override void onClick()
    {
        //TODO fonction en cours

        GameObject goJoueur = ClientScene.FindLocalObject(this.idJoueurPossesseur);

        if (null != goJoueur)
        {
            Joueur joueur = goJoueur.GetComponent <Joueur> ();

            if (isMovableByPlayer(joueur))
            {
                EventTask eventTask = EventTaskUtils.getEventTaskEnCours();
                if (this.etatSelectionnable == SelectionnableUtils.ETAT_SELECTIONNABLE && null != eventTask && eventTask is EventTaskChoixCible)
                {
                    ((EventTaskChoixCible)eventTask).ListCibleChoisie.Add(this);
                }
                else if (joueur.CarteSelectionne is CarteVaisseauMetier && ((CarteVaisseauMetier)joueur.CarteSelectionne).isCapableAttaquer() &&
                         joueur.RessourceCarburant.StockWithCapacity >= ((CarteVaisseauMetier)joueur.CarteSelectionne).getConsomationCarburant())
                {
                    joueur.CmdPayerRessource(joueur.RessourceCarburant.TypeRessource, ((CarteVaisseauMetier)joueur.CarteSelectionne).getConsomationCarburant());
                    joueur.CarteSelectionne.deplacerCarte(this, joueur.netId, NetworkInstanceId.Invalid);

                    //TODO doit on mettre tous de suite le bouton (si le déplacement est impossible?
                    BoutonTour boutonJoueur = joueur.GoPlateau.GetComponentInChildren <BoutonTour> ();
                    if (null != boutonJoueur)
                    {
                        boutonJoueur.CmdSetEtatBouton(BoutonTour.enumEtatBouton.attaque);
                    }
                }
                else if (listNomCarteExeption.Contains(joueur.CarteSelectionne.name))
                {
                    //TODO carte en exception
                }
            }
        }
    }
Exemplo n.º 14
0
    public void RpcResurrectUnit(NetworkInstanceId unitId)
    {
        GameObject findUnit = null;
        Unit       unitToRes;

        if (isServer)
        {
            findUnit = NetworkServer.FindLocalObject(unitId);
        }
        else if (isClient)
        {
            findUnit = ClientScene.FindLocalObject(unitId);
        }

        if (findUnit != null)
        {
            unitToRes = findUnit.GetComponent <Unit> ();
            myHealBot.ResurrectUnit(unitToRes);
        }
        else
        {
            Debug.Log("Error: Resurrection Unit Not Found");
        }
    }
Exemplo n.º 15
0
        /// <summary>
        /// Sets the owner of the region
        /// </summary>
        /// <param name="ownerId">id of the owner</param>
#pragma warning disable 618
        [ClientRpc] public void RpcSetOwner(NetworkInstanceId ownerId)
#pragma warning restore 618
        {
            Assert.IsTrue(isClient, "Run RpcSetOwner only clientside");
            if (Owner && Building)
            {
                Owner.VictoryPoints.RemoveVictoryPoints(Building.GainedVictoryPoints);
            }
#pragma warning disable 618
            if (ownerId != NetworkInstanceId.Invalid)
            {
                var owner = ClientScene.FindLocalObject(ownerId).GetComponent <Player>();
#pragma warning restore 618
                Owner = owner;
                Color color = owner.PlayerColor;
                color.a = 0.3f;
                RegionOwnerOverlay.GetComponent <SpriteRenderer>().color = color;
            }
            else
            {
                Owner = null;
                RegionOwnerOverlay.GetComponent <SpriteRenderer>().color = new Color(0, 0, 0, 0);
            }
        }
Exemplo n.º 16
0
    void ClientReceiveUpdate(NetworkMessage message)
    {
        ServerStateUpdate updateMessage = message.ReadMessage <ServerStateUpdate>();

        NetworkInstanceId netId    = new NetworkInstanceId(updateMessage.netId);
        GameObject        foundObj = ClientScene.FindLocalObject(netId);

        if (foundObj == null)
        {
            return;
        }

        if (message.conn.playerControllers[0].unetView.netId == netId)
        {
            PlayerNetworkTransform networkTransform = foundObj.GetComponent <PlayerNetworkTransform>();
            //Update the player network transform from the server
            networkTransform.OnServerFrame(
                new PlayerState(
                    updateMessage.Origin,
                    updateMessage.Velocity
                    )
                );
        }
    }
Exemplo n.º 17
0
 void OnChangeOwnerId(NetworkInstanceId ownerId)
 {
     // Equipped
     if (_owner == null)
     {
         _owner = ClientScene.FindLocalObject(ownerId).GetComponent <PlayerController>();
         if (!_owner)
         {
             Debug.LogError("Could not get PlayerController for equipment owner.");
         }
         if (isServer)
         {
             GetComponent <NetworkIdentity>().AssignClientAuthority(_owner.connectionToClient);
         }
         _owner.equippedItem     = this;
         transform.parent        = _owner.transform;
         transform.localPosition = equippedLocalPosition;
         transform.localRotation = Quaternion.Euler(equippedLocalRotation);
         _particles.Stop();
         _trigger.enabled = false;
         SendMessage("OnEquip", SendMessageOptions.DontRequireReceiver);
     }
     else
     {
         // Dropped
         if (isServer)
         {
             GetComponent <NetworkIdentity>().RemoveClientAuthority(_owner.connectionToClient);
         }
         _owner.equippedItem = null;
         _owner           = null;
         transform.parent = null;
         StartCoroutine(Drop());
         SendMessage("OnDrop", SendMessageOptions.DontRequireReceiver);
     }
 }
Exemplo n.º 18
0
    private void RelicUpdated(NetworkInstanceId relicId)
    {
        /* Make sure the id isn't invalid */
        if (relicId == NetworkInstanceId.Invalid)
        {
            return;
        }

        /* Save the relic id */
        this.relicId = relicId;

        /* Get the relic object */
        GameObject relicObj = ClientScene.FindLocalObject(relicId);

        if (relicObj == null)
        {
            Debug.LogError("PlayerRelicManager Client: Server sent us a bad network instance id for our relic! " + relicId.Value);
            return;
        }

        /* Get the relic component */
        relic = relicObj.GetComponent <PlayerRelic>();
        if (relic == null)
        {
            Debug.LogError("PlayerRelicManager Client: Server sent us a bad network instance id for our relic! " + relicId.Value);
            return;
        }

        /* We own this relic */
        relic.SetRelicManager(this);

        if (debug)
        {
            Debug.Log("PlayeRelicManager Client: We have received our player relic object.");
        }
    }
Exemplo n.º 19
0
        private void AddMergeGroup()
        {
            //Since merging units require the selected units count to be a multiple of 2, we need to check to make sure they are a multiple of 2.
            //Else, ignore the final selected unit.
            //Going to change this into network code, to sync up merging.
            GameObject        ownerObject = null, mergerObject = null;
            List <GameObject> used = new List <GameObject>();

            for (int i = this.selectionManager.selectedObjects.Count - 1; i >= 0; i--)
            {
                if (used.Contains(this.selectionManager.selectedObjects[i]))
                {
                    continue;
                }
                ownerObject = this.selectionManager.selectedObjects[i];
                GameUnit ownerUnit = ownerObject.GetComponent <GameUnit>();
                for (int j = i - 1; j >= 0; j--)
                {
                    if (used.Contains(this.selectionManager.selectedObjects[j]))
                    {
                        continue;
                    }
                    mergerObject = this.selectionManager.selectedObjects[j];
                    GameUnit mergerUnit = mergerObject.GetComponent <GameUnit>();
                    this.doNotAllowMerging = false;
                    if (ownerUnit.level == 1 && mergerUnit.level == 1)
                    {
                        CheckAvailableResource();
                    }
                    if (ownerUnit.level == mergerUnit.level && !ownerUnit.isMerging && !mergerUnit.isMerging && !this.doNotAllowMerging)
                    {
                        used.Add(this.selectionManager.selectedObjects[i]);
                        used.Add(this.selectionManager.selectedObjects[j]);

                        NetworkIdentity identity = this.GetComponent <NetworkIdentity>();
                        if (identity != null)
                        {
                            CmdAddMerge(ownerObject, mergerObject, ownerUnit.hasAuthority, (this.isServer ? NetworkServer.FindLocalObject(identity.netId) : ClientScene.FindLocalObject(identity.netId)));
                        }

                        this.selectionManager.selectedObjects.RemoveAt(i);
                        i--;
                        this.selectionManager.selectedObjects.RemoveAt(j);
                        j--;
                        break;
                    }
                }
            }
        }
Exemplo n.º 20
0
    private void Update()
    {
        if (ControlledByPlayer == NetworkInstanceId.Invalid)
        {
            return;
        }

        //don't start it too early:
        if (!isServer && !PlayerManager.LocalPlayer)
        {
            return;
        }

        //only perform the rest of the update if the weapon is in the hand of the local player or
        //we are the server
        if (!isServer && PlayerManager.LocalPlayer != ClientScene.FindLocalObject(ControlledByPlayer))
        {
            return;
        }

        //update the time until the next shot can happen
        if (FireCountDown > 0)
        {
            FireCountDown -= Time.deltaTime;
            //prevents the next projectile taking miliseconds longer than it should
            if (FireCountDown < 0)
            {
                FireCountDown = 0;
            }
        }

        //this will only be executed on the server since only the server
        //maintains the queued actions
        if (queuedShots.Count > 0 && FireCountDown <= 0)
        {
            //fire the next shot in the queue
            DequeueAndProcessServerShot();
        }

        if (queuedUnload && queuedShots.Count == 0)
        {
            // done processing shot queue,
            // perform the queued unload action, causing all clients and server to update their version of this Weapon
            //due to the syncvar hook
            MagNetID     = NetworkInstanceId.Invalid;
            queuedUnload = false;
        }
        if (queuedLoadMagNetID != NetworkInstanceId.Invalid && queuedShots.Count == 0)
        {
            //done processing shot queue, perform the reload, causing all clients and server to update their version of this Weapon
            //due to the syncvar hook
            MagNetID           = queuedLoadMagNetID;
            queuedLoadMagNetID = NetworkInstanceId.Invalid;
        }

        //rest of the Update is only needed for the weapon if it is held by the local player
        if (PlayerManager.LocalPlayer != ClientScene.FindLocalObject(ControlledByPlayer))
        {
            return;
        }

        //check if burst should stop if the weapon is held by the local player
        if (Input.GetMouseButtonUp(0))
        {
            StopAutomaticBurst();
        }
    }
Exemplo n.º 21
0
    /// <summary>
    /// Attempt to fire a single shot of the weapon (this is called once per bullet for a burst of automatic fire). This
    /// should be invoked by the client when they want to perform a shot.
    /// </summary>
    /// <param name="isSuicide">if the shot should be a suicide shot, striking the weapon holder</param>
    /// <returns>true iff something happened</returns>
    private bool AttemptToFireWeapon(bool isSuicide)
    {
        PlayerMove shooter = ClientScene.FindLocalObject(ControlledByPlayer).GetComponent <PlayerMove>();

        if (!shooter.allowInput || shooter.isGhost)
        {
            return(false);
        }
        //suicide is not allowed in some cases.
        isSuicide = isSuicide && AllowSuicide;
        //ignore if we are hovering over UI
        if (EventSystem.current.IsPointerOverGameObject())
        {
            return(false);
        }

        //if we have no mag/clip loaded play empty sound
        if (CurrentMagazine == null)
        {
            StopAutomaticBurst();
            PlayEmptySFX();
            return(true);
        }
        //if we are out of ammo for this weapon eject magazine and play out of ammo sfx
        else if (Projectile != null && CurrentMagazine.ammoRemains <= 0 && FireCountDown <= 0)
        {
            StopAutomaticBurst();
            RequestUnload(CurrentMagazine);
            OutOfAmmoSFX();
            return(true);
        }
        else
        {
            //if we have a projectile to shoot, we have ammo and we are not waiting to be allowed to shoot again, Fire!
            if (Projectile != null && CurrentMagazine.ammoRemains > 0 && FireCountDown <= 0)
            {
                //fire a single round if its a semi or automatic weapon
                if (WeaponType == WeaponType.SemiAutomatic || WeaponType == WeaponType.FullyAutomatic)
                {
                    //shot direction
                    Vector2 dir = (Camera.main.ScreenToWorldPoint(Input.mousePosition) -
                                   PlayerManager.LocalPlayer.transform.position).normalized;
                    if (!isServer)
                    {
                        //we're a client, request the server to make us shoot
                        RequestShootMessage.Send(gameObject, dir, Projectile.name, UIManager.DamageZone, isSuicide,
                                                 PlayerManager.LocalPlayer);
                        //Prediction (client bullets don't do any damage)
                        dir = ApplyRecoil(dir);
                        DisplayShot(PlayerManager.LocalPlayer, dir, UIManager.DamageZone, isSuicide);
                    }
                    else
                    {
                        // we are the server, go ahead and shoot
                        ServerShoot(PlayerManager.LocalPlayer, dir, UIManager.DamageZone, isSuicide);
                    }

                    if (WeaponType == WeaponType.FullyAutomatic)
                    {
                        PlayerManager.LocalPlayerScript.mouseInputController.OnMouseDownDir(dir);
                    }
                }

                if (WeaponType == WeaponType.FullyAutomatic && !InAutomaticAction)
                {
                    StartBurst(isSuicide);
                }
                else
                {
                    ContinueBurst(isSuicide);
                }

                return(true);
            }
        }

        return(true);
    }
Exemplo n.º 22
0
    private void generateButtons(NetworkInstanceId pid)
    {
        float x           = 0;
        float buttonWidth = 32f;

        GameObject obj;

        if (isClient)
        {
            obj = ClientScene.FindLocalObject(pid);
        }
        else
        {
            obj = NetworkServer.FindLocalObject(pid);
        }

        Player player = obj.GetComponent <Player> ();

        foreach (Mod mod in mods)
        {
            if (mod.costToRemove > 0)
            {
                GameObject removeButton = (GameObject)Instantiate(Resources.Load("ModifierIcon"));

                if (isPositive(mod))
                {
                    removeButton.GetComponent <Image> ().color = Color.green;
                }
                Transform parent = GameObject.Find("Canvas").transform.Find("ReadoutPanel/Readout Scroll/Viewport/ReadoutDisplay/Mods");
                Transform dummy  = parent.Find("Dummy");
                removeButton.transform.SetParent(parent, false);
                removeButton.transform.position = new Vector3(dummy.position.x + x, dummy.position.y, dummy.position.z);

                removeButton.GetComponent <Image> ().sprite = icons [mod.icon];
                Text   tmpText   = removeButton.transform.Find("Text").GetComponent <Text> ();
                Button tmpButton = removeButton.GetComponent <Button> ();


                removeButton.GetComponent <ModIcon> ().setTooltipText(modToString(mod) + "\nRemoval cost:" + " $" + mod.costToRemove + "");
                if (building.ownedBy(player.netId))
                {
                    string toRemove = mod.modName;
                    int    price    = mod.costToRemove;
                    tmpButton.onClick.AddListener(delegate {
                        player.CmdRemoveMod(toRemove, price, pid, gameObject.GetComponent <NetworkIdentity> ().netId);
                    });
                }
                buttons.Add(removeButton);

                x += buttonWidth;
            }
            else
            {
                GameObject removeButton = (GameObject)Instantiate(Resources.Load("ModifierIcon"));

                if (isPositive(mod))
                {
                    removeButton.GetComponent <Image> ().color = Color.green;
                }
                removeButton.transform.SetParent(GameObject.Find("Canvas").transform.Find("ReadoutPanel").transform, false);
                removeButton.transform.localPosition = new Vector3(x, -32, 0);
                removeButton.transform.localScale    = new Vector3(1, 1, 1);

                removeButton.GetComponent <Image> ().sprite = icons [mod.icon];


                removeButton.GetComponent <ModIcon> ().setTooltipText(modToString(mod));

                buttons.Add(removeButton);
                x += buttonWidth;
            }
        }
    }
Exemplo n.º 23
0
        void Update()
        {
            if (ControlledByPlayer == NetworkInstanceId.Invalid)
            {
                return;
            }

            //don't start it too early:
            if (!PlayerManager.LocalPlayer)
            {
                return;
            }

            //Only update if it is inhand of localplayer
            if (PlayerManager.LocalPlayer != ClientScene.FindLocalObject(ControlledByPlayer))
            {
                return;
            }

            if (FireCountDown > 0)
            {
                FireCountDown -= Time.deltaTime;
                //prevents the next projectile taking miliseconds longer than it should
                if (FireCountDown < 0)
                {
                    FireCountDown = 0;
                }
            }

            //Check if magazine in opposite hand or if unloading
            if (Input.GetKeyDown(KeyCode.E))
            {
                //PlaceHolder for click UI
                GameObject currentHandItem = UIManager.Hands.CurrentSlot.Item;
                GameObject otherHandItem   = UIManager.Hands.OtherSlot.Item;
                string     hand;

                if (currentHandItem != null)
                {
                    if (CurrentMagazine == null)
                    {
                        //RELOAD
                        MagazineBehaviour magazine = currentHandItem.GetComponent <MagazineBehaviour>();

                        if (magazine != null && otherHandItem.GetComponent <Weapon>() != null)
                        {
                            hand = UIManager.Hands.CurrentSlot.eventName;
                            Reload(currentHandItem, hand);
                        }
                    }
                    else
                    {
                        //UNLOAD
                        Weapon weapon = currentHandItem.GetComponent <Weapon>();

                        if (weapon != null && otherHandItem == null)
                        {
                            ManualUnload(CurrentMagazine);
                        }
                    }
                }
            }

            if (Input.GetMouseButtonUp(0))
            {
                InAutomaticAction = false;

                //remove recoil after shooting is released
                CurrentRecoilVariance = 0;
            }

            if (InAutomaticAction && FireCountDown <= 0)
            {
                AttemptToFireWeapon();
            }
        }
Exemplo n.º 24
0
 public void RpcBasicAttack(GameObject b, Vector3 dir, Vector3 pos, NetworkInstanceId i)
 {
     b.GetComponent <IVBullet>().SetOwner(ClientScene.FindLocalObject(i).GetComponent <IVPlayer>());
     b.GetComponent <Rigidbody>().AddForce(dir * bulletspeed);
 }
Exemplo n.º 25
0
 void RpcCastedBuff(GameObject b, NetworkInstanceId id)
 {
     Debug.Log(ClientScene.FindLocalObject(id).name + " has been debuffed.");
     b.GetComponent <IVSkill>().SetOwner(ClientScene.FindLocalObject(id).GetComponent <IVPlayer>());
 }
Exemplo n.º 26
0
    public void setRentPrice(NetworkInstanceId pid, NetworkInstanceId buildingId, int rent)
    {
        GameObject p;

        p = NetworkServer.FindLocalObject(pid);
        if (p == null)
        {
            p = ClientScene.FindLocalObject(pid);
        }

        Player player = p.GetComponent <Player> ();

        if (priceInput != null)
        {
            priceInput.text = rent.ToString();
            priceInput.onValueChanged.RemoveAllListeners();
            priceInput.onValueChanged.AddListener(delegate {
                player.getRentComparison(buildingId, priceInput.text);
            });
            player.getRentComparison(buildingId, priceInput.text);

            priceInput.onEndEdit.RemoveAllListeners();
            priceInput.onEndEdit.AddListener(delegate {
                player.CmdSetRent(priceInput.text, buildingId);
            });
        }

        if (priceIncreaseButton != null)
        {
            priceIncreaseButton.onClick.RemoveAllListeners();
            priceIncreaseButton.onClick.AddListener(delegate {
                if (string.IsNullOrEmpty(priceInput.text))
                {
                    priceInput.text = "1";
                }
                else
                {
                    int tmp = int.Parse(priceInput.text);
                    tmp++;
                    priceInput.text = tmp.ToString();
                }
            });
        }

        if (priceDecreaseButton != null)
        {
            priceDecreaseButton.onClick.RemoveAllListeners();
            priceDecreaseButton.onClick.AddListener(delegate {
                if (string.IsNullOrEmpty(priceInput.text))
                {
                    priceInput.text = "0";
                }
                else
                {
                    int tmp = int.Parse(priceInput.text);
                    tmp--;
                    priceInput.text = tmp.ToString();
                }
            });
        }
    }
Exemplo n.º 27
0
 [Command] //Commands - which are called from the client and run on the server;
 public void CmdAddPlayerToSession(NetworkInstanceId clientID)
 {
     network_Client_Objects.Add(clientID, ClientScene.FindLocalObject(clientID));
     RpcUpdatePlayerCountOnClient(_syncedvars.PlayerCount + 1);
 }
Exemplo n.º 28
0
    // Update is called once per frame
    void FixedUpdate()
    {
        var health = GetComponent <Health>();

        if (health.IsAlive())
        {
            GetComponent <CharacterController>().enabled = true;
            if (!isLocalPlayer)
            {
                transform.GetChild(1).gameObject.SetActive(true);
            }
            if (!hasResetRagdoll)
            {
                hasResetRagdoll = true;
                if (transform.childCount == 3)
                {
                    Destroy(transform.GetChild(2).gameObject);
                }
                var ragdoll = Instantiate(RagdollPrefab);
                ragdoll.transform.parent = transform;
                ragdollMiddleBack        = ragdoll.transform.GetChild(1).GetChild(0).GetChild(0);
                ragdoll.SetActive(false);
                ragdoll.transform.localPosition = Vector3.zero;

                var skin = ragdoll.transform.GetChild(0).GetComponent <SkinnedMeshRenderer>();

                if (scoreBoard)
                {
                    var num = scoreBoard.getPlayerNum(netId);

                    if (isLocalPlayer)
                    {
                        ui.transform.Find("Head").GetChild(0).GetChild(0).GetComponent <MeshRenderer>().material = playerMats[num];
                    }

                    skin.material = playerMats[num];

                    switch (num)
                    {
                    case 0:
                        name = "Boyo";
                        break;

                    case 1:
                        name = "Mama";
                        break;

                    case 2:
                        name = "Papa";
                        break;

                    case 3:
                        name = "Loco";
                        break;

                    default:
                        break;
                    }
                }
            }
        }
        else
        {
            GetComponent <CharacterController>().enabled = false;
            hasResetRagdoll = false;
            if (transform.childCount > 2)
            {
                if (!transform.GetChild(2).gameObject.activeInHierarchy)
                {
                    transform.GetChild(2).gameObject.SetActive(true);
                    ragdollMiddleBack.GetComponent <Rigidbody>().velocity = velocity * 10.0f;
                }
            }
            transform.GetChild(1).gameObject.SetActive(false);
        }
        if (!isLocalPlayer)
        {
            var ham  = transform.GetChild(1).GetChild(0);
            var skin = ham.GetComponent <SkinnedMeshRenderer>();

            if (scoreBoard)
            {
                var num = scoreBoard.getPlayerNum(netId);

                skin.material = playerMats[num];
            }

            return;
        }
        if (!ui.activeInHierarchy)
        {
            var num = scoreBoard.getPlayerNum(netId);
            ui.SetActive(true);
            ui.transform.Find("Head").GetChild(0).GetChild(0).GetComponent <MeshRenderer>().material = playerMats[num];
        }

        if (recoilTimer > 0)
        {
            recoilTimer -= Time.fixedDeltaTime;
        }

        if (!health.IsAlive())
        {
            var combat = GetComponent <Combat>();

            var killer = ClientScene.FindLocalObject(combat.killerId);

            camera.parent = null;

            camera.position = killer.GetComponent <PlayerMovement>().ragdollMiddleBack.transform.position + new Vector3(2, 2, 2);

            camera.LookAt(killer.GetComponent <PlayerMovement>().ragdollMiddleBack);

            if (!hasResetCombat)
            {
                hasResetCombat = true;
                combat.Reset();

                var soundVersion = (int)Mathf.Floor(Random.value * 3);

                playDeathSound(transform.position, soundVersion);
                CmdPlayDeathSound(soundVersion);

                //ragdollMiddleBack.GetComponent<Rigidbody>().velocity = velocity;
            }
            respawnTimer -= Time.fixedDeltaTime;
            if (respawnTimer <= 0)
            {
                respawnTimer = 3.0f;
                health.CmdResetHealth();

                var spawn      = spawnPoints[Random.Range(0, spawnPoints.Length)].transform;
                var spawnPoint = spawn.position;

                velocity           = Vector3.zero;
                transform.position = spawnPoint + new Vector3(0, 1, 0);
                transform.rotation = spawn.rotation;
                gunRotation        = 0.0f;
            }
        }
        else
        {
            hasResetCombat = false;
            if (camera)
            {
                camera.parent = gunHolder.GetChild(0);

                camera.localPosition = new Vector3(0, 0, 0);

                camera.localRotation = Quaternion.identity;
            }
        }

        var mouseX = Input.GetAxisRaw("Mouse X");
        var mouseY = Input.GetAxisRaw("Mouse Y");

        var mouseSensitivityAdjust = Input.GetAxis("Mouse Sensitivity");

        xSensitivity += mouseSensitivityAdjust;
        ySensitivity += mouseSensitivityAdjust;

        if (xSensitivity < 1)
        {
            xSensitivity = 1;
        }
        if (ySensitivity < 1)
        {
            ySensitivity = 1;
        }

        if (!health.IsAlive())
        {
            mouseX = 0;
            mouseY = 0;
        }

        var sphereCheck = Physics.CheckSphere(transform.position - new Vector3(0f, 0.6f, 0f), 0.5f, 1 << 8);

        sphereCheck = sphereCheck || Physics.CheckSphere(transform.position - new Vector3(0f, 0.7f, 0f), 0.5f, 1 << 8);

        var newGrounded = sphereCheck && velocity.y <= 0;

        if (!isGrounded && newGrounded)
        {
            if (velocity.y < -16f)
            {
                if (health.IsAlive())
                {
                    GetComponent <Combat>().CmdSetKillMessage(health.netId, "self", "floor");
                }
                health.CmdDecreaseHealth((-velocity.y - 16f) * 2f, 2);
            }
        }

        isGrounded = newGrounded;

        gunRotation            += mouseY * Time.deltaTime * ySensitivity;
        gunRotation             = ClampAngle(gunRotation, -90, 90);
        gunHolder.localRotation = Quaternion.AngleAxis(gunRotation, new Vector3(-1, 0, 0));

        transform.localRotation = transform.localRotation * Quaternion.AngleAxis(mouseX * Time.fixedDeltaTime * xSensitivity, new Vector3(0, 1, 0));

        var rotation = transform.rotation;

        if (isGrounded)
        {
            groundedCounter = 0.0f;
            walkMove();
            var ray = new Ray(transform.position + new Vector3(0, -1, 0), Vector3.down);

            RaycastHit hit;

            Physics.Raycast(ray, out hit);

            var normal = hit.normal;

            var rotationToNormal = Quaternion.FromToRotation(Vector3.up, normal);

            footstepTimer += velocity.magnitude * Time.fixedDeltaTime * 0.4f;

            characterController.Move(rotationToNormal * velocity * Time.fixedDeltaTime);

            var s = Vector3.Dot(velocity, transform.forward);

            var f = velocity;
            f.y = 0;

            //print("Speed: " + f);

            if (s < 0)
            {
                animator.SetFloat("Forward", -f.magnitude / 5.0f);
            }
            else
            {
                animator.SetFloat("Forward", f.magnitude / 5.0f);
                animator.SetBool("Jump", false);
            }
        }
        else
        {
            //animator.SetBool("Backflip", false);
            if (groundedCounter < 0.1f)
            {
                CheckJump();
            }
            else
            {
                //animator.SetBool("Backflip", false);
            }
            groundedCounter += Time.fixedDeltaTime;
            airMove();
            footstepTimer = 0.5f;
            characterController.Move(velocity * Time.fixedDeltaTime);

            //CmdSetAnimatorForward(0.0f);

            //animator.SetFloat("Forward", 0.0f);
        }

        var sign       = Mathf.Sign(Mathf.Sin(footstepTimer * Mathf.PI));
        var remainder  = footstepTimer - Mathf.Floor(footstepTimer);
        var cameraRoll = (-1.0f + remainder * 2.0f) * sign;


        gunHolder.GetChild(0).transform.localRotation = Quaternion.AngleAxis(cameraRoll * 0.5f, Vector3.forward);
        gunHolder.GetChild(1).transform.localRotation = Quaternion.AngleAxis(cameraRoll * 10.0f, Vector3.up) * Quaternion.AngleAxis(90, Vector3.right);
        gunHolder.GetChild(2).transform.localRotation = Quaternion.AngleAxis(cameraRoll * 10.0f, Vector3.up);
        gunHolder.GetChild(3).transform.localRotation = Quaternion.AngleAxis(cameraRoll * 10.0f, Vector3.up);
        gunHolder.GetChild(4).transform.localRotation = Quaternion.AngleAxis(cameraRoll * 10.0f, Vector3.up);
        gunHolder.GetChild(5).transform.localRotation = Quaternion.AngleAxis(cameraRoll * 10.0f, Vector3.up);

        var t = (footstepTimer + 0.5f) * 2.0f;

        sign      = Mathf.Sign(Mathf.Sin(t * Mathf.PI));
        remainder = t - Mathf.Floor(t);
        var bobble = (-1.0f + remainder * 2.0f) * sign;

        gunHolder.GetChild(0).transform.localPosition = new Vector3(0, 0.025f + bobble * 0.025f, 0);

        if (swapWeaponTimer > 0.0f)
        {
            swapWeaponTimer -= Time.fixedDeltaTime * 4;

            for (var i = 1; i < 6; i++)
            {
                gunHolder.GetChild(i).localRotation = gunHolder.GetChild(i).localRotation *Quaternion.AngleAxis(swapWeaponTimer * 90.0f, Vector3.right);;
            }
            //gunHolder.localRotation = gunHolder.localRotation * Quaternion.AngleAxis(swapWeaponTimer * 90.0f, new Vector3(0, -1, 0));
        }
    }
Exemplo n.º 29
0
 void OnReceiveHPMsg(NetworkMessage _msg)
 {
     NetworkMessageHandler.ChangeHPMessage msg = _msg.ReadMessage <NetworkMessageHandler.ChangeHPMessage>();
     ClientScene.FindLocalObject(Manager.Instance.GetNetIDFromConnectedNetID(msg.ObjectID)).GetComponent <SphereScript>().HP = msg.HP;
     ClientScene.FindLocalObject(Manager.Instance.GetNetIDFromConnectedNetID(msg.ObjectID)).GetComponent <SphereScript>().UpdateHp();
 }
Exemplo n.º 30
0
        /// <summary>
        /// Deserialize a message from the network.
        /// </summary>
        /// <remarks>
        /// Only receives what it needs and decompresses floats if you chose to.
        /// </remarks>
        /// <param name="writer">The Networkreader to read from.</param>
        override public void Deserialize(NetworkReader reader)
        {
            // The first received byte tells us what we need to be syncing.
            byte syncInfoByte        = reader.ReadByte();
            bool syncPosition        = shouldSyncPosition(syncInfoByte);
            bool syncRotation        = shouldSyncRotation(syncInfoByte);
            bool syncScale           = shouldSyncScale(syncInfoByte);
            bool syncVelocity        = shouldSyncVelocity(syncInfoByte);
            bool syncAngularVelocity = shouldSyncAngularVelocity(syncInfoByte);

            NetworkInstanceId netID = reader.ReadNetworkId();
            int syncIndex           = (int)reader.ReadPackedUInt32();

            state.ownerTimestamp = (int)reader.ReadPackedUInt32();

            // Find the GameObject
            GameObject ob = null;

            if (NetworkServer.active)
            {
                ob = NetworkServer.FindLocalObject(netID);
            }
            else
            {
                ob = ClientScene.FindLocalObject(netID);
            }

            if (!ob)
            {
                Debug.LogWarning("Could not find target for network state message.");
                return;
            }

            // It doesn't matter which SmoothSync is returned since they all have the same list.
            smoothSync = ob.GetComponent <SmoothSync>();

            // If we want the server to relay non-owned object information out to other clients, set these variables so we know what we need to send.
            if (NetworkServer.active && !smoothSync.hasAuthority)
            {
                state.serverShouldRelayPosition        = syncPosition;
                state.serverShouldRelayRotation        = syncRotation;
                state.serverShouldRelayScale           = syncScale;
                state.serverShouldRelayVelocity        = syncVelocity;
                state.serverShouldRelayAngularVelocity = syncAngularVelocity;
            }

            // Find the correct object to sync according to the syncIndex.
            for (int i = 0; i < smoothSync.childObjectSmoothSyncs.Length; i++)
            {
                if (smoothSync.childObjectSmoothSyncs[i].syncIndex == syncIndex)
                {
                    smoothSync = smoothSync.childObjectSmoothSyncs[i];
                }
            }

            if (!smoothSync)
            {
                Debug.LogWarning("Could not find target for network state message.");
                return;
            }

            // Read position.
            if (syncPosition)
            {
                if (smoothSync.isPositionCompressed)
                {
                    if (smoothSync.isSyncingXPosition)
                    {
                        state.position.x = HalfHelper.Decompress(reader.ReadUInt16());
                    }
                    if (smoothSync.isSyncingYPosition)
                    {
                        state.position.y = HalfHelper.Decompress(reader.ReadUInt16());
                    }
                    if (smoothSync.isSyncingZPosition)
                    {
                        state.position.z = HalfHelper.Decompress(reader.ReadUInt16());
                    }
                }
                else
                {
                    if (smoothSync.isSyncingXPosition)
                    {
                        state.position.x = reader.ReadSingle();
                    }
                    if (smoothSync.isSyncingYPosition)
                    {
                        state.position.y = reader.ReadSingle();
                    }
                    if (smoothSync.isSyncingZPosition)
                    {
                        state.position.z = reader.ReadSingle();
                    }
                }
            }
            else
            {
                if (smoothSync.stateCount > 0)
                {
                    state.position = smoothSync.stateBuffer[0].position;
                }
                else
                {
                    state.position = smoothSync.getPosition();
                }
            }
            // Read rotation.
            if (syncRotation)
            {
                Vector3 rot = new Vector3();
                if (smoothSync.isRotationCompressed)
                {
                    if (smoothSync.isSyncingXRotation)
                    {
                        rot.x = HalfHelper.Decompress(reader.ReadUInt16());
                    }
                    if (smoothSync.isSyncingYRotation)
                    {
                        rot.y = HalfHelper.Decompress(reader.ReadUInt16());
                    }
                    if (smoothSync.isSyncingZRotation)
                    {
                        rot.z = HalfHelper.Decompress(reader.ReadUInt16());
                    }
                    state.rotation = Quaternion.Euler(rot);
                }
                else
                {
                    if (smoothSync.isSyncingXRotation)
                    {
                        rot.x = reader.ReadSingle();
                    }
                    if (smoothSync.isSyncingYRotation)
                    {
                        rot.y = reader.ReadSingle();
                    }
                    if (smoothSync.isSyncingZRotation)
                    {
                        rot.z = reader.ReadSingle();
                    }
                    state.rotation = Quaternion.Euler(rot);
                }
            }
            else
            {
                if (smoothSync.stateCount > 0)
                {
                    state.rotation = smoothSync.stateBuffer[0].rotation;
                }
                else
                {
                    state.rotation = smoothSync.getRotation();
                }
            }
            // Read scale.
            if (syncScale)
            {
                if (smoothSync.isScaleCompressed)
                {
                    if (smoothSync.isSyncingXScale)
                    {
                        state.scale.x = HalfHelper.Decompress(reader.ReadUInt16());
                    }
                    if (smoothSync.isSyncingYScale)
                    {
                        state.scale.y = HalfHelper.Decompress(reader.ReadUInt16());
                    }
                    if (smoothSync.isSyncingZScale)
                    {
                        state.scale.z = HalfHelper.Decompress(reader.ReadUInt16());
                    }
                }
                else
                {
                    if (smoothSync.isSyncingXScale)
                    {
                        state.scale.x = reader.ReadSingle();
                    }
                    if (smoothSync.isSyncingYScale)
                    {
                        state.scale.y = reader.ReadSingle();
                    }
                    if (smoothSync.isSyncingZScale)
                    {
                        state.scale.z = reader.ReadSingle();
                    }
                }
            }
            else
            {
                if (smoothSync.stateCount > 0)
                {
                    state.scale = smoothSync.stateBuffer[0].scale;
                }
                else
                {
                    state.scale = smoothSync.getScale();
                }
            }
            // Read velocity.
            if (syncVelocity)
            {
                if (smoothSync.isVelocityCompressed)
                {
                    if (smoothSync.isSyncingXVelocity)
                    {
                        state.velocity.x = HalfHelper.Decompress(reader.ReadUInt16());
                    }
                    if (smoothSync.isSyncingYVelocity)
                    {
                        state.velocity.y = HalfHelper.Decompress(reader.ReadUInt16());
                    }
                    if (smoothSync.isSyncingZVelocity)
                    {
                        state.velocity.z = HalfHelper.Decompress(reader.ReadUInt16());
                    }
                }
                else
                {
                    if (smoothSync.isSyncingXVelocity)
                    {
                        state.velocity.x = reader.ReadSingle();
                    }
                    if (smoothSync.isSyncingYVelocity)
                    {
                        state.velocity.y = reader.ReadSingle();
                    }
                    if (smoothSync.isSyncingZVelocity)
                    {
                        state.velocity.z = reader.ReadSingle();
                    }
                }
            }
            else
            {
                state.velocity = Vector3.zero;
            }
            // Read anguluar velocity.
            if (syncAngularVelocity)
            {
                if (smoothSync.isAngularVelocityCompressed)
                {
                    if (smoothSync.isSyncingXAngularVelocity)
                    {
                        state.angularVelocity.x = HalfHelper.Decompress(reader.ReadUInt16());
                    }
                    if (smoothSync.isSyncingYAngularVelocity)
                    {
                        state.angularVelocity.y = HalfHelper.Decompress(reader.ReadUInt16());
                    }
                    if (smoothSync.isSyncingZAngularVelocity)
                    {
                        state.angularVelocity.z = HalfHelper.Decompress(reader.ReadUInt16());
                    }
                }
                else
                {
                    if (smoothSync.isSyncingXAngularVelocity)
                    {
                        state.angularVelocity.x = reader.ReadSingle();
                    }
                    if (smoothSync.isSyncingYAngularVelocity)
                    {
                        state.angularVelocity.y = reader.ReadSingle();
                    }
                    if (smoothSync.isSyncingZAngularVelocity)
                    {
                        state.angularVelocity.z = reader.ReadSingle();
                    }
                }
            }
            else
            {
                state.angularVelocity = Vector3.zero;
            }
        }