Search Unity

Resolved Sync position Issue

Discussion in 'Netcode for GameObjects' started by Valentinhon, May 4, 2023.

  1. Valentinhon

    Valentinhon

    Joined:
    Oct 20, 2019
    Posts:
    76
    Hello,

    I'm using Character Controller and State Machine to manage the movement and Animation of my player character. The rotation is coding directly without state machine.
    I'm using the tutorial of CodeMonkey Youtube channel to implement multiplayer with Unity Network for GameObject but I encounter a really early issue with syncing the position.
    I host a server via a build, let's say Build01. I move the player in this instance. Then with a second build, Build02, I'm joiining the frist player. I see the actual position of the player1 but if I moving it now, the second player can't see him moving. And The player1 can't see the Player 2 moving.
    both player can't see the animation either. Each player can move in its instance but can't see the other player moving.
    BUT player 1 can see the rotation of player 2 and vice versa.
    So I think the problem comes from Character Controller and/or my state machine.
    The player is in grounded state + Idle Substate and then, if I press WSAD key or a LeftStick Gamepad, the player pass to Grounded State + Walk Substate.

    It seems like the character Controller or the State machine don't communicate the .move function to the Network or receive a zéro vector in the .move function.

    Can someone please help me ?

    In the "Client Netwtok Transform" component, I've checked sync position in x, y and Z. Same with Rotation.

    Base State :
    Code (CSharp):
    1.  
    2. using UnityEngine;
    3. public abstract class CharacterBaseState
    4. {
    5.     private bool _isRootState = false; //Variable to tell if the concrete state is at the top of the state hierarchy
    6.     private CharacterStateMachine _ctx;
    7.     private CharacterStateFactory _factory;
    8.     private CharacterBaseState _currentSubState;
    9.     private CharacterBaseState _currentSuperState;
    10.  
    11.     protected bool IsRootState { set { _isRootState = value; } }
    12.     protected CharacterStateMachine Ctx { get { return _ctx; } }
    13.     protected CharacterStateFactory Factory { get { return _factory; } }
    14.  
    15.     public CharacterBaseState(CharacterStateMachine currentContext, CharacterStateFactory characterStateFactory)
    16.     {
    17.         _ctx = currentContext;
    18.         _factory = characterStateFactory;
    19.     }
    20.  
    21.     public abstract void EnterState();
    22.  
    23.     public abstract void UpdateState();
    24.  
    25.     public abstract void ExitState();
    26.  
    27.     public abstract void CheckSwitchState();
    28.  
    29.     public abstract void InitializeSubState();
    30.  
    31.     public void UpdateStates()
    32.     {
    33.  
    34.  
    35.         UpdateState();
    36.         if (_currentSubState != null)
    37.         {
    38.             _currentSubState.UpdateStates();
    39.         }
    40.  
    41.     }
    42.  
    43.     protected void SwitchState(CharacterBaseState newState)
    44.     {
    45.  
    46.  
    47.         //First we have to exit the current State
    48.         ExitState();
    49.         //Then we can "Enter" in a new state
    50.         newState.EnterState();
    51.         if (_isRootState) //We only switch tge context's current state if it's at the  top level of the state chain
    52.         {
    53.             //Finally the context set the "_currentState" to be the newState
    54.             _ctx.CurrentState = newState;
    55.         }
    56.         else if (_currentSuperState != null)
    57.         {
    58.             _currentSuperState.SetSubState(newState);
    59.         }
    60.     }
    61.  
    62.     protected void SetSuperState(CharacterBaseState  newSuperState)
    63.     {
    64.         _currentSuperState = newSuperState;
    65.     }
    66.  
    67.     protected void SetSubState(CharacterBaseState newSubState)
    68.     {
    69.         _currentSubState = newSubState;
    70.         newSubState.SetSuperState(this);
    71.     }
    72.  
    73.  
    74. }
    75.  
    Walk State :

    Code (CSharp):
    1.  
    2. using UnityEngine;
    3.  
    4. public class CharacterWalkingState : CharacterBaseState
    5. {
    6.     //Vector use to use the right animation regarding the direction where the player is looking at and the direction input
    7.     Vector3 VelocityAnimation;
    8.     public CharacterWalkingState(CharacterStateMachine currentContext, CharacterStateFactory characterStateFactory)
    9.     : base(currentContext, characterStateFactory) { }
    10.  
    11.     //Increase performance
    12.     int VelocityXHash;
    13.     int VelocityZHash;
    14.  
    15.     public override void EnterState()
    16.     {
    17.         ////Debug.Log("WELCOME TO THE WALK SUBSTATE2");
    18.         Ctx.Animator.SetBool(Ctx.IsWalkingHash, true);
    19.         VelocityXHash = Animator.StringToHash("Velocity X");
    20.         VelocityZHash = Animator.StringToHash("Velocity Z");
    21.     }
    22.  
    23.     public override void UpdateState()
    24.     {
    25.      
    26.  
    27.      
    28.         //Movement applied to the character
    29.         Ctx.AppliedMovementX = (Ctx.CurrentMovement.x * (Mathf.Cos(Ctx.CameraRotation * Mathf.PI / 180))) - (Ctx.CurrentMovement.y * (Mathf.Sin(Ctx.CameraRotation * Mathf.PI / 180)));
    30.         Ctx.AppliedMovementZ = (Ctx.CurrentMovement.y * (Mathf.Cos(Ctx.CameraRotation * Mathf.PI / 180))) + (Ctx.CurrentMovement.x * (Mathf.Sin(Ctx.CameraRotation * Mathf.PI / 180)));
    31.        
    32.         float _zDirzChara = Vector3.Angle(new Vector3(0,0,Ctx.AppliedMovementZ), Ctx.TransformForwardChara); //Angle between the Z input and the forward vector of the character
    33.         ////Debug.Log(" Angle _zDirzChara " + _zDirzChara);
    34.         float _xDirzChara = Vector3.Angle(new Vector3(Ctx.AppliedMovementX, 0, 0), Ctx.TransformForwardChara); //Angle between the X input and the forward vector of the character
    35.         ////Debug.Log(" Angle _xDirzChara " + _xDirzChara);
    36.         float _xDirxChara = Vector3.Angle(new Vector3(Ctx.AppliedMovementX, 0, 0), Ctx.TransformRightChara); //Angle between the X input and the right vector of the character
    37.         ////Debug.Log(" Angle _xDirxChara " + _xDirxChara);
    38.         float _zDirxChara = Vector3.Angle(new Vector3(0, 0, Ctx.AppliedMovementZ), Ctx.TransformRightChara); //Angle between the Z input and the right vector of the character
    39.         /*//Debug.Log(" Angle _zDirxChara " + _zDirxChara);
    40.         //Debug.Log("Angle Ctx.AppliedMovementX : " + Ctx.AppliedMovementX);
    41.         //Debug.Log("Angle Ctx.AppliedMovementZ : " + Ctx.AppliedMovementZ);
    42.         //Debug.Log("Angle Ctx.AppliedMovementX * Mathf.Cos(_xDirxChara) : " + Ctx.AppliedMovementX * Mathf.Cos(_xDirxChara * Mathf.PI / 180));
    43.         //Debug.Log("Angle Ctx.AppliedMovementZ * Mathf.Cos(_zDirxChara) : " + Ctx.AppliedMovementZ * Mathf.Cos(_zDirxChara * Mathf.PI / 180));
    44.         //Debug.Log("Angle Ctx.AppliedMovementZ * Mathf.Cos(_zDirzChara) : " + Ctx.AppliedMovementZ * Mathf.Cos(_zDirzChara * Mathf.PI / 180));
    45.         //Debug.Log("Angle Ctx.AppliedMovementX * Mathf.Cos(_xDirzChara) : " + Ctx.AppliedMovementX * Mathf.Cos(_xDirzChara * Mathf.PI / 180));
    46.         */
    47.         //Result on the animation of the direction Input and the direction where the character is looking at
    48.         VelocityAnimation.x = Mathf.Abs(Ctx.AppliedMovementX) * Mathf.Cos(_xDirxChara * Mathf.PI / 180) + Mathf.Abs(Ctx.AppliedMovementZ) * Mathf.Cos(_zDirxChara * Mathf.PI / 180);
    49.         VelocityAnimation.y = 0;
    50.         VelocityAnimation.z = Mathf.Abs(Ctx.AppliedMovementZ) * Mathf.Cos(_zDirzChara * Mathf.PI / 180) + Mathf.Abs(Ctx.AppliedMovementX) * Mathf.Cos(_xDirzChara * Mathf.PI / 180);
    51.         Vector3.Normalize(VelocityAnimation);
    52.        
    53.         Ctx.Animator.SetFloat(VelocityXHash, VelocityAnimation.x);
    54.         Ctx.Animator.SetFloat(VelocityZHash, VelocityAnimation.z);
    55.              
    56.         CheckSwitchState();
    57.     }
    58.  
    59.     public override void ExitState() { }
    60.  
    61.     public override void CheckSwitchState()
    62.     {
    63.         if(!Ctx.IsMovementPressed)
    64.         {
    65.             SwitchState(Factory.Idle());
    66.         }
    67.     }
    68.  
    69.     public override void InitializeSubState() { }
    70. }
    And finally the Character State Machine (Where the .Move() function is called )
    Code (CSharp):
    1.  
    2. using Unity.Netcode;
    3. using Cinemachine;
    4. using UnityEngine;
    5. using UnityEngine.InputSystem;
    6.  
    7.  
    8. //In the State Machine, this script is the "Context"
    9.  
    10. public class CharacterStateMachine : NetworkBehaviour
    11. {
    12.     //Declare reference variables
    13.     PlayerInput _playerInput;
    14.     CharacterController _charaController;
    15.     Animator _animator;
    16.  
    17.     //Variables to store optimized setter/getter parameter Ids
    18.     int _isMovingHash;
    19.  
    20.  
    21.     //Variables to store player input values
    22.     Vector2 _currentMovementInput = new Vector2(0, 0);
    23.     Vector3 _currentMovement = new Vector3(0, 0, 0);
    24.     Vector3 _appliedMovement = new Vector3(0, 0, 0);
    25.     bool _isMovementPressed = false;
    26.  
    27.  
    28.     //Movement variables
    29.     public float _speed;
    30.     public float _rotationSpeed = 15.0f;
    31.  
    32.     //Third person variable
    33.     Vector3 _cameraRelatioveMovement;
    34.     Quaternion lookRotation;
    35.     Vector3 _rotationRelativeMovement;
    36.  
    37.     //Gravity variables
    38.     //public float _groundedGravity = -0.05f;
    39.     public float _gravity = -9.81f;
    40.  
    41.     //Jump variables
    42.     bool _isJumpPressed = false;
    43.     float _initialJumpVelocity;
    44.     public float _maxJumpHeight = 0.75f;
    45.     public float _maxJumpTime = 2f;
    46.     bool _isJumping = false;
    47.     int _isJumpingHash;
    48.     int _isFallingHash;
    49.     //bool _isJumpingAnimating = false;//No more unnecessary variables from the previous implementation, without the State one.
    50.     bool _requireNewJumpPress;
    51.  
    52.     //State variables
    53.     [SerializeField]
    54.     CharacterBaseState _currentState;
    55.     CharacterStateFactory _states;
    56.  
    57.  
    58.     /*
    59.     public bool IsPickUpPressed { get { return GetComponent<PickUpBox>().GetIsPickUpPressed(); } set { GetComponent<PickUpBox>().SetIsPickUpPressed(value); } }
    60.  
    61.     public bool IsHoldingBox {  get { return GetComponent<PickUpBox>().GetIsHoldingBox(); } set { GetComponent<PickUpBox>().SetIsHoldingBox(value); } }
    62.     public bool IsRequireNewPickUpPress { get { return GetComponent<PickUpBox>().GetRequireNewPickUpPress(); } set { GetComponent<PickUpBox>().SetRequireNewPickUpPress(value); } }
    63.     */
    64.     //Camera variables
    65.     [SerializeField] private CinemachineVirtualCamera _cam;
    66.     bool requireNewCamRotationRightPress = false; //to force player to unpress the camRotation button to press it again to really camRotation
    67.     bool requireNewCamRotationLeftPress = false; //to force player to unpress the camRotation button to press it again to really camRotation
    68.  
    69.     bool _isCamRotationRightPressed;
    70.     bool _isCamRotationLeftPressed;
    71.     float _cameraRotation;
    72.     Vector2 mousePosition;
    73.     public float CameraRotation { get { return _cameraRotation; } }
    74.     bool _isLockRotToMove;
    75.     bool requireNewLockRotToMove = true;
    76.  
    77.     //Gamepad variables
    78.     public bool isGamepad;
    79.     Vector2 aimGamepad;
    80.     Vector2 aim;
    81.     float gamepadRotateRatio = 1000f;
    82.     bool _isLookWithRightStick;
    83.  
    84.     //Knock variables
    85.     float _knockForce;
    86.     Vector3 _knockVelocity;
    87.     Vector3 _dirOfShoot;
    88.     float _knockTime;
    89.  
    90.     //Recoil Impact
    91.     float _recoilImpactForce;
    92.     Vector3 _recoilImpactVelocity;
    93.     Vector3 _dirOfRecoilImpact;
    94.     float _recoilImpactTime;
    95.  
    96.  
    97.     //Getter and Setter of the State variables
    98.     public CharacterBaseState CurrentState { get { return _currentState; } set { _currentState = value; } }
    99.     public bool IsJumpPressed { get { return _isJumpPressed; } }
    100.     public Animator Animator { get { return _animator; } }
    101.  
    102.     public bool IsMovementPressed { get { return _isMovementPressed; } }
    103.     public int IsWalkingHash { get { return _isMovingHash; } set { _isMovingHash = value; } }
    104.  
    105.     public float AppliedMovementX { get { return _appliedMovement.x; }  set { _appliedMovement.x = value; } }
    106.     public float AppliedMovementZ { get { return _appliedMovement.z; } set { _appliedMovement.z = value; } }
    107.     public Vector2 CurrentMovement { get {return _currentMovementInput; } set { _currentMovementInput = value; } }
    108.     public bool IsJumping { set {_isJumping = value; }}
    109.     public int IsJumpingHash { get { return _isJumpingHash; } }
    110.     public float InitialJumpVelocity { get { return _initialJumpVelocity; } }
    111.  
    112.     public int IsFallingHash { get { return _isFallingHash; } set { _isFallingHash = value; } }
    113.  
    114.  
    115.     public float CurrentMovementY { get { return _currentMovement.y; } set { _currentMovement.y = value; } }
    116.     public float AppliedMovementY { get { return _appliedMovement.y; } set { _appliedMovement.y = value; } }
    117.  
    118.     public Vector3 ApplyMovement { get { return _appliedMovement; } }
    119.  
    120.  
    121.     public float Gravity { get { return _gravity; } set { _gravity = value; } }
    122.  
    123.     public bool RequireNewJumpPress { get { return _requireNewJumpPress; } set { _requireNewJumpPress = value; } }
    124.  
    125.     public CharacterController CharaController { get { return _charaController; } set { _charaController = value; } }
    126.  
    127.     public Quaternion Rotation { get { return transform.rotation; } }
    128.  
    129.     public Vector3 TransformForwardChara { get { return transform.forward; } }
    130.     public Vector3 TransformRightChara { get { return transform.right; } }
    131.  
    132.     public Vector3 TransformRelativeWorldToLocal { get { return transform.InverseTransformDirection(Vector3.forward); } }
    133.     public Vector3 TransformRelativeLocalToWorld { get { return transform.TransformDirection(transform.forward); } }
    134.  
    135.     public Vector3 CameraRelativeMovement { get { return _cameraRelatioveMovement; } }
    136.  
    137.  
    138.     Vector3 _positionToLookAt;
    139.  
    140.  
    141.     void Awake()
    142.     {
    143.         //Inityally set reference variable
    144.         _playerInput = new PlayerInput();
    145.         _charaController = GetComponent<CharacterController>();
    146.         _animator = GetComponent<Animator>();
    147.      
    148.         _speed = GetComponent<Stats_Character>().GetSpeed();
    149.      
    150.         _cam = GetComponent<VirtualCameraAssign>().GetVC();
    151.      
    152.     //Setup state
    153.         _states = new CharacterStateFactory(this);
    154.         _currentState = _states.Grounded();
    155.         _currentState.EnterState();
    156.  
    157.         //Set the parameter hash references
    158.         _isMovingHash = Animator.StringToHash("isMoving");
    159.         _isJumpingHash = Animator.StringToHash("isJumping");
    160.         _isFallingHash = Animator.StringToHash("isFalling");
    161.  
    162.     //Player Input
    163.         _playerInput.CharaControls.Move.started += OnMovementInput;
    164.         _playerInput.CharaControls.Move.canceled += OnMovementInput;
    165.         _playerInput.CharaControls.Move.performed += OnMovementInput;
    166.         _playerInput.CharaControls.Jump.started += OnJump;
    167.         _playerInput.CharaControls.Jump.canceled += OnJump;
    168.         _playerInput.CharaControls.CamRotationLeft.started += onCamRotationLeft;
    169.         _playerInput.CharaControls.CamRotationLeft.canceled += onCamRotationLeft;
    170.         _playerInput.CharaControls.CamRotationRight.started += onCamRotationRight;
    171.         _playerInput.CharaControls.CamRotationRight.canceled += onCamRotationRight;
    172.         _playerInput.CharaControls.Look.started += onRotationInput;
    173.         _playerInput.CharaControls.Look.canceled += onRotationInput;
    174.         _playerInput.CharaControls.Look.performed += onRotationInput;
    175.         _playerInput.CharaControls.LockRotToMove.started += onLockRotToMove;
    176.         _playerInput.CharaControls.LockRotToMove.canceled += onLockRotToMove;
    177.  
    178.         SetupJumpVariables();
    179.  
    180.     }
    181.  
    182.     //Set the intial velocity and gravity to use jump height and duration
    183.     void SetupJumpVariables()
    184.     {
    185.         float timeToApex = _maxJumpTime / 2;
    186.         _gravity = (-2 * _maxJumpHeight) / Mathf.Pow(timeToApex, 2);
    187.         _initialJumpVelocity = (2 * _maxJumpHeight) / timeToApex;
    188.     }
    189.  
    190.     // Start is called before the first frame update
    191.     void Start()
    192.     {
    193.      
    194.         if (_speed <= 0)
    195.         {
    196.             _speed = GetComponent<Stats_Character>().GetSpeed();
    197.         }
    198.     }
    199.  
    200.     // Update is called once per frame
    201.     void Update()
    202.     {
    203.      
    204.         if (!IsOwner)
    205.         {
    206.  
    207.             return;
    208.         }
    209.  
    210.         if (_cam == null)
    211.         {
    212.             _cam = GetComponent<VirtualCameraAssign>().GetVC();
    213.         }
    214.         HandleRotation();
    215.  
    216.  
    217.  
    218.         HandleMove();
    219.  
    220.         _currentState.UpdateStates();
    221.     }
    222.  
    223.  
    224.  
    225.     private void HandleMove()
    226.     {
    227.  
    228.         if(_knockTime > 0) //When player shoot, the character receive a force that make him get backward
    229.         {
    230.             _knockTime -= Time.deltaTime;
    231.             _knockVelocity = _dirOfShoot * (_knockForce * _knockTime);
    232.          
    233.         }
    234.         else if (_knockTime <= 0)
    235.         {
    236.             _knockVelocity = Vector3.zero;
    237.         }
    238.  
    239.         if (_recoilImpactTime > 0) // When player receive damage, the character receive a force that get him go to the direction opposite of where the force come from
    240.         {
    241.             _recoilImpactTime -= Time.deltaTime;
    242.             _recoilImpactVelocity = _dirOfRecoilImpact * (_recoilImpactForce * _recoilImpactTime);
    243.         }
    244.         else if (_recoilImpactTime <= 0)
    245.         {
    246.             _recoilImpactVelocity = Vector3.zero;
    247.         }
    248.  
    249.      
    250.  
    251.         _charaController.Move((_appliedMovement+_knockVelocity + _recoilImpactVelocity) * _speed * Time.deltaTime);
    252.  
    253.     }
    254.  
    255.  
    256.  
    257.     void HandleRotation()
    258.     {
    259.  
    260.         //Vector3 _positionToLookAt;
    261.         //Verify if the player is playing with a Gamepad
    262.         if (isGamepad)
    263.         {
    264.             //Debug.Log("Mathf.Abs(aim.x) : " + Mathf.Abs(aim.x));
    265.             // /Debug.Log("Mathf.Abs(aim.y) : " + Mathf.Abs(aim.y));
    266.             //Debug.Log("controllerDeadzone : " + controllerDeadzone);
    267.             //Debug.Log("isLookWithRightStick : " + _isLookWithRightStick);
    268.             //If the player is orienting the right joystick, the character will look to the direction poiting by this joystick
    269.             if (_isLookWithRightStick)
    270.             {
    271.                 aimGamepad.x = /*_isRunPressed ? */(aim.x) * (Mathf.Cos(_cameraRotation * Mathf.PI / 180)) - (aim.y) * (Mathf.Sin(_cameraRotation * Mathf.PI / 180));/* : _currentMovementInput.x;*/
    272.                 aimGamepad.y = /*_isRunPressed ? */(aim.y) * (Mathf.Cos(_cameraRotation * Mathf.PI / 180)) + (aim.x) * (Mathf.Sin(_cameraRotation * Mathf.PI / 180));/* : _currentMovementInput.y;*/
    273.  
    274.                 Vector3 playerDirection = Vector3.right * aimGamepad.x + Vector3.forward * aimGamepad.y;
    275.                 if (playerDirection.sqrMagnitude > 0.0f)
    276.                 {
    277.                     Quaternion newRotation = Quaternion.LookRotation(playerDirection, Vector3.up);
    278.                     transform.rotation = Quaternion.RotateTowards(transform.rotation, newRotation, gamepadRotateRatio * Time.deltaTime);
    279.                 }
    280.             }
    281.             //If Player doesn't use the Joystick, the character will look in the direction of the movement
    282.             else if (!_isLookWithRightStick)
    283.             {
    284.                 _positionToLookAt.x = (_currentMovementInput.x * (Mathf.Cos(_cameraRotation * Mathf.PI / 180))) - (_currentMovementInput.y * (Mathf.Sin(_cameraRotation * Mathf.PI / 180))); //_cameraRelatioveMovement.x instead of _currentMovementInput.x for a third person view
    285.                 _positionToLookAt.y = 0.0f;
    286.                 _positionToLookAt.z = (_currentMovementInput.y * (Mathf.Cos(_cameraRotation * Mathf.PI / 180))) + (_currentMovementInput.x * (Mathf.Sin(_cameraRotation * Mathf.PI / 180))); ;  //_cameraRelatioveMovement.y instead of _currentMovementInput.y for a third person view
    287.              
    288.                 Quaternion _currentRotation = transform.rotation;
    289.  
    290.                 if (_isMovementPressed)
    291.                 {
    292.                     //Create a new rotation based on where the player is currently pressing
    293.                     Quaternion _targetRotation = Quaternion.LookRotation(_positionToLookAt);
    294.                     transform.rotation = Quaternion.Slerp(_currentRotation, _targetRotation, _rotationSpeed * Time.deltaTime);
    295.                 }
    296.             }
    297.          
    298.         }
    299.         //If player is using a keyboard
    300.         else if (!isGamepad)
    301.         {
    302.  
    303.             //If RequireNewLockRotToMove is true the player will look to direction of the mouse
    304.             if (requireNewLockRotToMove)
    305.             {
    306.                 Debug.Log("2 Cam : " + _cam.transform.name);
    307.                 Ray ray = Camera.main.ScreenPointToRay(mousePosition);
    308.              
    309.                 if (Physics.Raycast(ray, out RaycastHit raycastHit, 100.0f, ~(1<<11)))
    310.                 {
    311.                    _positionToLookAt = raycastHit.point;
    312.                    //_positionToLookAt.y = 1.5f;
    313.  
    314.                    LookAt(_positionToLookAt);
    315.                 }
    316.             }
    317.             //If RequireNewLockRotToMove is false, the character will look in the direction of the movement
    318.             else if (!requireNewLockRotToMove)
    319.             {
    320.                 Debug.Log("4 Cam : " + _cam.transform.name);
    321.                 _positionToLookAt.x = (_currentMovementInput.x * (Mathf.Cos(_cameraRotation * Mathf.PI / 180))) - (_currentMovementInput.y * (Mathf.Sin(_cameraRotation * Mathf.PI / 180))); //_cameraRelatioveMovement.x instead of _currentMovementInput.x for a third person view
    322.                 _positionToLookAt.y = 0.0f;
    323.                 _positionToLookAt.z = (_currentMovementInput.y * (Mathf.Cos(_cameraRotation * Mathf.PI / 180))) + (_currentMovementInput.x * (Mathf.Sin(_cameraRotation * Mathf.PI / 180))); ;  //_cameraRelatioveMovement.y instead of _currentMovementInput.y for a third person view
    324.  
    325.                 Quaternion _currentRotation = transform.rotation;
    326.  
    327.                 if (_isMovementPressed)
    328.                 {
    329.                     //Create a new rotation based on where the player is currently pressing
    330.                     Quaternion _targetRotation = Quaternion.LookRotation(_positionToLookAt);
    331.                     transform.rotation = Quaternion.Slerp(_currentRotation, _targetRotation, _rotationSpeed * Time.deltaTime);
    332.                 }
    333.             }
    334.             //Debug.Log("Camera Rotation : " + _cameraRotation);
    335.         }
    336.     }
    337.  
    338.  
    339.  
    340.     public void LookAt(Vector3 lookPoint) // Use to have the player looking where the mouse is
    341.     {
    342.         Vector3 direction = (lookPoint - transform.position);
    343.      
    344.         lookRotation = Quaternion.LookRotation(new Vector3(direction.x, 0.0f, direction.z));
    345.      
    346.      
    347.         transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime * _rotationSpeed);
    348.     }
    349.  
    350.     void OnMovementInput(InputAction.CallbackContext context) //Use to detect the WSAD or leftstick input
    351.     {
    352.  
    353.         _currentMovementInput = context.ReadValue<Vector2>();
    354.         _currentMovement.x = _currentMovementInput.x;
    355.         _currentMovement.z = _currentMovementInput.y;
    356.         _isMovementPressed = _currentMovementInput.x != 0 || _currentMovementInput.y != 0;
    357.     }
    358.     void OnJump(InputAction.CallbackContext context) //Use to detect jump button pressed
    359.     {
    360.         _isJumpPressed = context.ReadValueAsButton();
    361.         _requireNewJumpPress = false;
    362.     }
    363.  
    364.     void onCamRotationRight(InputAction.CallbackContext context) //Rotate the camera around player anti-clockwise
    365.     {
    366.  
    367.         _isCamRotationRightPressed = context.ReadValueAsButton();
    368.         requireNewCamRotationRightPress = false;
    369.         _cameraRotation = _cam.GetComponent<CameraControl>().GetCameraRotation();
    370.  
    371.  
    372.     }
    373.     void onCamRotationLeft(InputAction.CallbackContext context) //Rotate the Camera around player clockwise
    374.     {
    375.  
    376.         _isCamRotationLeftPressed = context.ReadValueAsButton();
    377.         requireNewCamRotationLeftPress = false;
    378.         _cameraRotation = _cam.GetComponent<CameraControl>().GetCameraRotation();
    379.  
    380.  
    381.     }
    382.  
    383.     void onRotationInput(InputAction.CallbackContext context) //If player use the right stick, the character  will look ind the direction of the stick and if player don't use the right stick, the character will look in the direction of the movement
    384.     {
    385.         mousePosition = context.ReadValue<Vector2>();
    386.         aim = context.ReadValue<Vector2>();
    387.      
    388.         if (context.performed && isGamepad)
    389.         {
    390.             _isLookWithRightStick = true;
    391.         }
    392.         else if (context.canceled && isGamepad)
    393.         {
    394.             _isLookWithRightStick = false;
    395.         }
    396.     }
    397.  
    398.     void onLockRotToMove(InputAction.CallbackContext context)
    399.     {
    400.         _isLockRotToMove = context.ReadValueAsButton();
    401.         if (_isLockRotToMove && requireNewLockRotToMove)
    402.         {
    403.             ////Debug.Log("Require new lock to move 1 : " + requireNewLockRotToMove);
    404.             requireNewLockRotToMove = false;
    405.             ////Debug.Log("Require new lock to move 2 : " + requireNewLockRotToMove);
    406.             return;
    407.         }
    408.         else if (_isLockRotToMove && !requireNewLockRotToMove)
    409.         {
    410.             ////Debug.Log("Require new lock to move 3 : " + requireNewLockRotToMove);
    411.             requireNewLockRotToMove = true;
    412.             ////Debug.Log("Require new lock to move 4 : " + requireNewLockRotToMove);
    413.             return;
    414.         }
    415.      
    416.     }
    417.  
    418.     //Setting of knock due shooting
    419.     public void SetKnockVariables(float knockForce, float knocTime)
    420.     {
    421.         _knockForce = knockForce;
    422.         _knockTime = knocTime;
    423.         _dirOfShoot = -transform.forward;
    424.     }
    425.  
    426.     public void SetImpactRecoil(float impactRecoilForce, float impactRecoilTime, Vector3 impactDir)
    427.     {
    428.  
    429.         _recoilImpactForce = impactRecoilForce;
    430.         _recoilImpactTime = impactRecoilTime;
    431.         _dirOfRecoilImpact = impactDir;
    432.  
    433.     }
    434.  
    435.  
    436.  
    437.     void OnEnable()
    438.     {
    439.         //Enable the chara controls action map
    440.         _playerInput.CharaControls.Enable();
    441.     }
    442.  
    443.     void OnDisable()
    444.     {
    445.         //Disable the chara controls action map
    446.         _playerInput.CharaControls.Disable();
    447.     }
    448. }
    449.  
     
    Last edited: May 4, 2023
  2. Valentinhon

    Valentinhon

    Joined:
    Oct 20, 2019
    Posts:
    76
    I forget to say that the "Character Controller" component of player1 is detected by player2 and vice versa because Player 2 can't go through player 1, there is bodyblock and that's what I want .
     
  3. Valentinhon

    Valentinhon

    Joined:
    Oct 20, 2019
    Posts:
    76
    Please can someone help me ?
     
  4. LaneFox

    LaneFox

    Joined:
    Jun 29, 2011
    Posts:
    7,518
    That's a lot of code we don't need to read.

    NetworkTransform
    has no client authority by default. See here for a solution.
     
  5. NoelStephens_Unity

    NoelStephens_Unity

    Unity Technologies

    Joined:
    Feb 12, 2022
    Posts:
    258
    To add to what LaneFox posted,
    With CharacterController you will want to disable the CharacterController on non-owners you will want to disable the CharacterController. Personally, I typically handle this in the owner/client authoritative NetworkTransform and that would look something like:
    Code (CSharp):
    1.     [DisallowMultipleComponent]
    2.     public class ClientNetworkTransform : NetworkTransform
    3.     {
    4.         private CharacterController m_CharacterController;
    5.  
    6.         private void Awake()
    7.         {
    8.             m_CharacterController = GetComponent<CharacterController>();
    9.         }
    10.         /// <summary>
    11.         /// Used to determine who can write to this transform. Owner client only.
    12.         /// This imposes state to the server. This is putting trust on your clients. Make sure no security-sensitive features use this transform.
    13.         /// </summary>
    14.         protected override bool OnIsServerAuthoritative()
    15.         {
    16.             return false;
    17.         }
    18.  
    19.         public override void OnNetworkSpawn()
    20.         {
    21.             if (!IsOwner)
    22.             {
    23.                 m_CharacterController.enabled = false;
    24.             }
    25.             base.OnNetworkSpawn();
    26.         }
    27.     }