Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

Resolved Client doesn't move

Discussion in 'Netcode for GameObjects' started by VexsDEV, Mar 24, 2023.

  1. VexsDEV

    VexsDEV

    Joined:
    Aug 28, 2021
    Posts:
    2
    Hi I was trying to get a simple first person controller to work. But the client can't move at all.
    Here is the controller for the player (it's based on the preset by Unity):
    Code (CSharp):
    1. public class FirstPersonController : NetworkBehaviour
    2.     {
    3.         [Header("Player")]
    4.         [Tooltip("Move speed of the character in m/s")]
    5.         public float MoveSpeed = 4.0f;
    6.         [Tooltip("Sprint speed of the character in m/s")]
    7.         public float SprintSpeed = 6.0f;
    8.         [Tooltip("Rotation speed of the character")]
    9.         public float RotationSpeed = 1.0f;
    10.         [Tooltip("Acceleration and deceleration")]
    11.         public float SpeedChangeRate = 10.0f;
    12.  
    13.         [Space(10)]
    14.         [Tooltip("The height the player can jump")]
    15.         public float JumpHeight = 1.2f;
    16.         [Tooltip("The character uses its own gravity value. The engine default is -9.81f")]
    17.         public float Gravity = -15.0f;
    18.  
    19.         [Space(10)]
    20.         [Tooltip("Time required to pass before being able to jump again. Set to 0f to instantly jump again")]
    21.         public float JumpTimeout = 0.1f;
    22.         [Tooltip("Time required to pass before entering the fall state. Useful for walking down stairs")]
    23.         public float FallTimeout = 0.15f;
    24.  
    25.         [Header("Player Grounded")]
    26.         [Tooltip("If the character is grounded or not. Not part of the CharacterController built in grounded check")]
    27.         public bool Grounded = true;
    28.         [Tooltip("Useful for rough ground")]
    29.         public float GroundedOffset = -0.14f;
    30.         [Tooltip("The radius of the grounded check. Should match the radius of the CharacterController")]
    31.         public float GroundedRadius = 0.5f;
    32.         [Tooltip("What layers the character uses as ground")]
    33.         public LayerMask GroundLayers;
    34.  
    35.         [Header("Cinemachine")]
    36.         [Tooltip("The follow target set in the Cinemachine Virtual Camera that the camera will follow")]
    37.         public GameObject CinemachineCameraTarget;
    38.         public GameObject PlayerFollowCamera;
    39.         [Tooltip("The Noise Settings to use when the player is moving")]
    40.         public NoiseSettings noiseSettingsWhilePlaying;
    41.         [Tooltip("How far in degrees can you move the camera up")]
    42.         public float TopClamp = 90.0f;
    43.         [Tooltip("How far in degrees can you move the camera down")]
    44.         public float BottomClamp = -90.0f;
    45.  
    46.         // cinemachine
    47.         private float _cinemachineTargetPitch;
    48.  
    49.         // player
    50.         private float _speed;
    51.         private float _rotationVelocity;
    52.         private float _verticalVelocity;
    53.         private float _terminalVelocity = 53.0f;
    54.  
    55.         // timeout deltatime
    56.         private float _jumpTimeoutDelta;
    57.         private float _fallTimeoutDelta;
    58.  
    59.    
    60. #if ENABLE_INPUT_SYSTEM && STARTER_ASSETS_PACKAGES_CHECKED
    61.         private PlayerInput _playerInput;
    62. #endif
    63.         private CharacterController _controller;
    64.         private StarterAssetsInputs _input;
    65.         private GameObject _mainCamera;
    66.  
    67.         private const float _threshold = 0.01f;
    68.  
    69.         private bool IsCurrentDeviceMouse
    70.         {
    71.             get
    72.             {
    73.                 #if ENABLE_INPUT_SYSTEM && STARTER_ASSETS_PACKAGES_CHECKED
    74.                 return _playerInput.currentControlScheme == "KeyboardMouse";
    75.                 #else
    76.                 return false;
    77.                 #endif
    78.             }
    79.         }
    80.  
    81.         private void Awake()
    82.         {
    83.             // get a reference to our main camera
    84.             if (_mainCamera == null)
    85.             {
    86.                 _mainCamera = GameObject.FindGameObjectWithTag("MainCamera");
    87.             }
    88.         }
    89.  
    90.         private void Start()
    91.         {
    92.             if (!IsOwner) return;
    93.             _controller = GetComponent<CharacterController>();
    94.             _input = GetComponent<StarterAssetsInputs>();
    95. #if ENABLE_INPUT_SYSTEM && STARTER_ASSETS_PACKAGES_CHECKED
    96.             _playerInput = GetComponent<PlayerInput>();
    97. #else
    98.             Debug.LogError( "Starter Assets package is missing dependencies. Please use Tools/Starter Assets/Reinstall Dependencies to fix it");
    99. #endif
    100.  
    101.             // reset our timeouts on start
    102.             _jumpTimeoutDelta = JumpTimeout;
    103.             _fallTimeoutDelta = FallTimeout;
    104.            
    105.             GameObject _playerFollowCamera = Instantiate(PlayerFollowCamera, transform.position, transform.rotation);
    106.            
    107.             CinemachineBasicMultiChannelPerlin cinemachineBasicMultiChannelPerlin = _playerFollowCamera.GetComponent<CinemachineVirtualCamera>()
    108.                 .GetCinemachineComponent<CinemachineBasicMultiChannelPerlin>();
    109.             cinemachineBasicMultiChannelPerlin.m_NoiseProfile = noiseSettingsWhilePlaying;
    110.             _playerFollowCamera.GetComponent<CinemachineVirtualCamera>().Follow = CinemachineCameraTarget.transform;
    111.         }
    112.  
    113.         private void Update()
    114.         {
    115.             if(!IsOwner) return;
    116.             JumpAndGravity();
    117.             GroundedCheck();
    118.             Move();
    119.         }
    120.  
    121.         private void LateUpdate()
    122.         {
    123.             if(!IsOwner) return;
    124.             CameraRotation();
    125.         }
    126.  
    127.         private void GroundedCheck()
    128.         {
    129.             // set sphere position, with offset
    130.             Vector3 spherePosition = new Vector3(transform.position.x, transform.position.y - GroundedOffset, transform.position.z);
    131.             Grounded = Physics.CheckSphere(spherePosition, GroundedRadius, GroundLayers, QueryTriggerInteraction.Ignore);
    132.         }
    133.  
    134.         private void CameraRotation()
    135.         {
    136.             // if there is an input
    137.             if (_input.look.sqrMagnitude >= _threshold)
    138.             {
    139.                 //Don't multiply mouse input by Time.deltaTime
    140.                 float deltaTimeMultiplier = IsCurrentDeviceMouse ? 1.0f : Time.deltaTime;
    141.                
    142.                 _cinemachineTargetPitch += _input.look.y * RotationSpeed * deltaTimeMultiplier;
    143.                 _rotationVelocity = _input.look.x * RotationSpeed * deltaTimeMultiplier;
    144.  
    145.                 // clamp our pitch rotation
    146.                 _cinemachineTargetPitch = ClampAngle(_cinemachineTargetPitch, BottomClamp, TopClamp);
    147.  
    148.                 // Update Cinemachine camera target pitch
    149.                 CinemachineCameraTarget.transform.localRotation = Quaternion.Euler(_cinemachineTargetPitch, 0.0f, 0.0f);
    150.  
    151.                 // rotate the player left and right
    152.                 transform.Rotate(Vector3.up * _rotationVelocity);
    153.             }
    154.         }
    155.  
    156.         private void Move()
    157.         {
    158.             // set target speed based on move speed, sprint speed and if sprint is pressed
    159.             float targetSpeed = _input.sprint ? SprintSpeed : MoveSpeed;
    160.  
    161.             // a simplistic acceleration and deceleration designed to be easy to remove, replace, or iterate upon
    162.  
    163.             // note: Vector2's == operator uses approximation so is not floating point error prone, and is cheaper than magnitude
    164.             // if there is no input, set the target speed to 0
    165.             if (_input.move == Vector2.zero) targetSpeed = 0.0f;
    166.  
    167.             // a reference to the players current horizontal velocity
    168.             float currentHorizontalSpeed = new Vector3(_controller.velocity.x, 0.0f, _controller.velocity.z).magnitude;
    169.  
    170.             float speedOffset = 0.1f;
    171.             float inputMagnitude = _input.analogMovement ? _input.move.magnitude : 1f;
    172.  
    173.             // accelerate or decelerate to target speed
    174.             if (currentHorizontalSpeed < targetSpeed - speedOffset || currentHorizontalSpeed > targetSpeed + speedOffset)
    175.             {
    176.                 // creates curved result rather than a linear one giving a more organic speed change
    177.                 // note T in Lerp is clamped, so we don't need to clamp our speed
    178.                 _speed = Mathf.Lerp(currentHorizontalSpeed, targetSpeed * inputMagnitude, Time.deltaTime * SpeedChangeRate);
    179.  
    180.                 // round speed to 3 decimal places
    181.                 _speed = Mathf.Round(_speed * 1000f) / 1000f;
    182.             }
    183.             else
    184.             {
    185.                 _speed = targetSpeed;
    186.             }
    187.  
    188.             // normalise input direction
    189.             Vector3 inputDirection = new Vector3(_input.move.x, 0.0f, _input.move.y).normalized;
    190.  
    191.             // note: Vector2's != operator uses approximation so is not floating point error prone, and is cheaper than magnitude
    192.             // if there is a move input rotate player when the player is moving
    193.             if (_input.move != Vector2.zero)
    194.             {
    195.                 // move
    196.                 inputDirection = transform.right * _input.move.x + transform.forward * _input.move.y;
    197.             }
    198.  
    199.             // move the player
    200.             _controller.Move(inputDirection.normalized * (_speed * Time.deltaTime) + new Vector3(0.0f, _verticalVelocity, 0.0f) * Time.deltaTime);
    201.         }
    202.  
    203.         private void JumpAndGravity()
    204.         {
    205.             if (Grounded)
    206.             {
    207.                 // reset the fall timeout timer
    208.                 _fallTimeoutDelta = FallTimeout;
    209.  
    210.                 // stop our velocity dropping infinitely when grounded
    211.                 if (_verticalVelocity < 0.0f)
    212.                 {
    213.                     _verticalVelocity = -2f;
    214.                 }
    215.  
    216.                 // Jump
    217.                 if (_input.jump && _jumpTimeoutDelta <= 0.0f)
    218.                 {
    219.                     // the square root of H * -2 * G = how much velocity needed to reach desired height
    220.                     _verticalVelocity = Mathf.Sqrt(JumpHeight * -2f * Gravity);
    221.                 }
    222.  
    223.                 // jump timeout
    224.                 if (_jumpTimeoutDelta >= 0.0f)
    225.                 {
    226.                     _jumpTimeoutDelta -= Time.deltaTime;
    227.                 }
    228.             }
    229.             else
    230.             {
    231.                 // reset the jump timeout timer
    232.                 _jumpTimeoutDelta = JumpTimeout;
    233.  
    234.                 // fall timeout
    235.                 if (_fallTimeoutDelta >= 0.0f)
    236.                 {
    237.                     _fallTimeoutDelta -= Time.deltaTime;
    238.                 }
    239.  
    240.                 // if we are not grounded, do not jump
    241.                 _input.jump = false;
    242.             }
    243.  
    244.             // apply gravity over time if under terminal (multiply by delta time twice to linearly speed up over time)
    245.             if (_verticalVelocity < _terminalVelocity)
    246.             {
    247.                 _verticalVelocity += Gravity * Time.deltaTime;
    248.             }
    249.         }
    250.  
    251.         private static float ClampAngle(float lfAngle, float lfMin, float lfMax)
    252.         {
    253.             if (lfAngle < -360f) lfAngle += 360f;
    254.             if (lfAngle > 360f) lfAngle -= 360f;
    255.             return Mathf.Clamp(lfAngle, lfMin, lfMax);
    256.         }
    257.  
    258.         private void OnDrawGizmosSelected()
    259.         {
    260.             Color transparentGreen = new Color(0.0f, 1.0f, 0.0f, 0.35f);
    261.             Color transparentRed = new Color(1.0f, 0.0f, 0.0f, 0.35f);
    262.  
    263.             if (Grounded) Gizmos.color = transparentGreen;
    264.             else Gizmos.color = transparentRed;
    265.  
    266.             // when selected, draw a gizmo in the position of, and matching radius of, the grounded collider
    267.             Gizmos.DrawSphere(new Vector3(transform.position.x, transform.position.y - GroundedOffset, transform.position.z), GroundedRadius);
    268.         }
    269.     }
     
  2. VexsDEV

    VexsDEV

    Joined:
    Aug 28, 2021
    Posts:
    2
    Never mind got it to work I just deleted the new Input System