Advertisement
DugganSC

Untitled

Jan 16th, 2024
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.08 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. [SerializeField]
  19. private bool _isGrounded = false;
  20.  
  21. private CharacterController _characterController;
  22. private PlayerInputs _playerInputs;
  23.  
  24. private void Start()
  25. {
  26. if (!TryGetComponent<CharacterController>(out _characterController)) {
  27. Debug.LogError("Character controller could not be found for the player");
  28. Debug.Break();
  29. }
  30. }
  31.  
  32. private void Awake()
  33. {
  34. _playerInputs = new PlayerInputs();
  35. _playerInputs.Default.Enable();
  36. _playerInputs.Default.Jump.performed += Jump_performed;
  37. // _playerInputs.Default.Interact.performed += Interact_performed;
  38. }
  39.  
  40. private void Jump_performed(UnityEngine.InputSystem.InputAction.CallbackContext obj)
  41. {
  42. if (_isGrounded)
  43. {
  44. Vector3 velocity = _characterController.velocity;
  45. velocity.y += _jumpHeight;
  46. _characterController.Move(velocity * Time.deltaTime);
  47. }
  48. }
  49.  
  50. private void FixedUpdate()
  51. {
  52. // Because being grounded is a physics thing, it's better to check it during FixedUpdate
  53. // and then cache it.
  54. _isGrounded = _characterController.isGrounded;
  55. }
  56.  
  57. private void Update()
  58. {
  59. Vector2 playerMovement = _playerInputs.Default.Movement.ReadValue<Vector2>();
  60. Vector3 velocity = _characterController.velocity;
  61. if (_isGrounded)
  62. {
  63. velocity = new Vector3(0, 0, playerMovement.x) * _moveSpeed;
  64. } else
  65. {
  66. velocity.y -= _gravity;
  67. }
  68. transform.Translate(velocity);
  69.  
  70. _characterController.Move(velocity * Time.deltaTime);
  71. }
  72. }
  73.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement