Почти полный код:
public class Player : MonoBehaviour
{
[SerializeField] private float _speedwalk;
[SerializeField] private float _gravity;
[SerializeField] private float _jumpPower;
[SerializeField] private float _speedRun;
[SerializeField] private float _crouchSpeed;
private CharacterController _characterController;
private Vector3 _walkDirection;
private Vector3 _velocity;
public float _speed;
private void Start()
{
_speed = _speedwalk;
_characterController = GetComponent<CharacterController>();
}
private void Update()
{
Jump(Input.GetKey(
KeyCode.Space ) && _characterController.isGrounded);
Run(Input.GetKey(KeyCode.LeftShift));
Crouch(Input.GetKey(KeyCode.LeftControl));
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
_walkDirection = transform.right * x + transform.forward * z;
}
private void FixedUpdate()
{
Walk(_walkDirection);
DoGravity(_characterController.isGrounded);
}
private void Walk(Vector3 direction)
{
_characterController.Move(direction * _speedwalk * Time.fixedDeltaTime);
}
private void Jump(bool canJump)
{
if (canJump)
_velocity.y = _jumpPower;
}
private void Run(bool canRun)
{
_speedwalk = canRun ? _speedRun : _speed;
}
private void Crouch(bool canCrouch)
{
_characterController.height = canCrouch ? 1f : 2f;
_speedwalk = canCrouch ? _crouchSpeed : _speed;
}
private void Update()
{
Run(Input.GetKey(KeyCode.LeftShift));
Crouch(Input.GetKey(KeyCode.LeftControl));
}
private void Run(bool canRun)
{
_speedwalk = canRun ? _speedRun : _speed;
}
private void Crouch(bool canCrouch)
{
_characterController.height = canCrouch ? 1f : 2f;
_speedwalk = canCrouch ? _crouchSpeed : _speed;
}