Advertisement
DugganSC

Untitled

Jan 16th, 2024 (edited)
34
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.35 KB | None | 0 0
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using Unity.VisualScripting;
  5. using UnityEngine;
  6. using UnityEngine.InputSystem;
  7. using UnityEngine.InputSystem.XR;
  8.  
  9. public class Player : MonoBehaviour
  10. {
  11. [SerializeField]
  12. private float _moveSpeed = 5f;
  13. [SerializeField]
  14. private float _gravity = 10f;
  15. [SerializeField]
  16. private float _jumpHeight = 50f;
  17.  
  18. private float _yVelocity;
  19.  
  20. [SerializeField]
  21. private bool _isGrounded = false;
  22.  
  23. private float _lastGrounded = -1;
  24.  
  25. private CharacterController _characterController;
  26. private PlayerInputs _playerInputs;
  27.  
  28. [SerializeField]
  29. private float _groundingThreshold = 0.1f;
  30.  
  31. private void Start()
  32. {
  33. if (!TryGetComponent<CharacterController>(out _characterController)) {
  34. Debug.LogError("Character controller could not be found for the player");
  35. Debug.Break();
  36. }
  37. }
  38.  
  39. private void Awake()
  40. {
  41. _playerInputs = new PlayerInputs();
  42. _playerInputs.Default.Enable();
  43. _playerInputs.Default.Jump.performed += Jump_performed;
  44. }
  45.  
  46. private bool RecentlyGrounded()
  47. {
  48. return Time.time - _lastGrounded <= _groundingThreshold;
  49. }
  50.  
  51. private void Jump_performed(UnityEngine.InputSystem.InputAction.CallbackContext obj)
  52. {
  53. if (_isGrounded)
  54. {
  55. Debug.Log("Jumping");
  56. Vector3 velocity = _characterController.velocity;
  57. _yVelocity += _jumpHeight;
  58. _isGrounded = false;
  59. }
  60. }
  61.  
  62. private void FixedUpdate()
  63. {
  64. // Because being grounded is a physics thing, it's better to check it during FixedUpdate
  65. // and then cache it.
  66. _isGrounded = _characterController.isGrounded;
  67. if (_isGrounded)
  68. {
  69. _lastGrounded = Time.time;
  70. }
  71. }
  72.  
  73. private void Update()
  74. {
  75. Vector2 playerMovement = _playerInputs.Default.Movement.ReadValue<Vector2>();
  76. Vector3 velocity = _characterController.velocity;
  77. if (_isGrounded)
  78. {
  79. velocity = new Vector3(0, 0, playerMovement.x) * _moveSpeed;
  80. } else
  81. {
  82. _yVelocity -= _gravity;
  83. }
  84.  
  85. velocity.y = _yVelocity;
  86.  
  87. _characterController.Move(velocity * Time.deltaTime);
  88. }
  89. }
  90.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement