Advertisement
FlyingFrog

Untitled

Mar 7th, 2024
20
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.46 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.InputSystem;
  5.  
  6. public class PlayerMover : MonoBehaviour
  7. {
  8. [SerializeField] private float _currentMoveSpeed;
  9. private float _standartSpeed;
  10.  
  11.  
  12.  
  13. [SerializeField] private float _rotationFactorPerFrame = 1;
  14.  
  15. private CharacterController _characterController;
  16. private PlayerInput _playerInput;
  17. private Vector2 _currentMovementInput;
  18. private Vector3 _currentMovement;
  19. private bool _isMovementPressed;
  20.  
  21. public float MoveSpeed => _currentMoveSpeed;
  22.  
  23. private void Awake()
  24. {
  25. _playerInput = new PlayerInput();
  26. _characterController = GetComponent<CharacterController>();
  27.  
  28. _playerInput.CharacterControl.Move.started += OnMovementInput;
  29. _playerInput.CharacterControl.Move.canceled += OnMovementInput;
  30. _playerInput.CharacterControl.Move.performed += OnMovementInput;
  31. }
  32. private void Start () {
  33. _standartSpeed =_currentMoveSpeed;
  34. }
  35.  
  36. private void OnEnable()
  37. {
  38. _playerInput.CharacterControl.Enable();
  39. }
  40.  
  41. private void OnDisable()
  42. {
  43. _playerInput.CharacterControl.Disable();
  44. }
  45.  
  46. private void Update()
  47. {
  48. HandleRotation();
  49. _characterController.Move(_currentMovement * _currentMoveSpeed * Time.deltaTime);
  50. }
  51.  
  52. private void OnMovementInput(InputAction.CallbackContext context)
  53. {
  54. _currentMovementInput = context.ReadValue<Vector2>();
  55. _currentMovement.x = _currentMovementInput.x;
  56. _currentMovement.z = _currentMovementInput.y;
  57. _isMovementPressed = _currentMovementInput.x != 0 || _currentMovementInput.y != 0;
  58. }
  59.  
  60. private void HandleRotation()
  61. {
  62. Vector3 positionToLookAt;
  63.  
  64. positionToLookAt.x = _currentMovement.x;
  65. positionToLookAt.y = 0.0f;
  66. positionToLookAt.z = _currentMovement.z;
  67.  
  68. Quaternion currentRotation = transform.rotation;
  69.  
  70. if (_isMovementPressed)
  71. {
  72. Quaternion targetRotation = Quaternion.LookRotation(positionToLookAt);
  73. transform.rotation = Quaternion.Slerp(currentRotation, targetRotation, _rotationFactorPerFrame * Time.deltaTime);
  74. }
  75. }
  76. public void IncreasMoveSpeed (float newSpeed)
  77. {
  78. _currentMoveSpeed = newSpeed;
  79. }
  80.  
  81. public void SetStandartSpeed()
  82. {
  83. _currentMoveSpeed =_standartSpeed;
  84. }
  85. }
  86.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement