Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using Unity.VisualScripting;
- using UnityEngine;
- using UnityEngine.InputSystem;
- using UnityEngine.InputSystem.XR;
- public class Player : MonoBehaviour
- {
- [SerializeField]
- private float _moveSpeed = 5f;
- [SerializeField]
- private float _gravity = 10f;
- [SerializeField]
- private float _jumpHeight = 50f;
- private float _yVelocity;
- [SerializeField]
- private bool _isGrounded = false;
- private float _lastGrounded = -1;
- private CharacterController _characterController;
- private PlayerInputs _playerInputs;
- [SerializeField]
- private float _groundingThreshold = 0.1f;
- private void Start()
- {
- if (!TryGetComponent<CharacterController>(out _characterController)) {
- Debug.LogError("Character controller could not be found for the player");
- Debug.Break();
- }
- }
- private void Awake()
- {
- _playerInputs = new PlayerInputs();
- _playerInputs.Default.Enable();
- _playerInputs.Default.Jump.performed += Jump_performed;
- }
- private bool RecentlyGrounded()
- {
- return Time.time - _lastGrounded <= _groundingThreshold;
- }
- private void Jump_performed(UnityEngine.InputSystem.InputAction.CallbackContext obj)
- {
- if (_isGrounded)
- {
- Debug.Log("Jumping");
- Vector3 velocity = _characterController.velocity;
- _yVelocity += _jumpHeight;
- _isGrounded = false;
- }
- }
- private void FixedUpdate()
- {
- // Because being grounded is a physics thing, it's better to check it during FixedUpdate
- // and then cache it.
- _isGrounded = _characterController.isGrounded;
- if (_isGrounded)
- {
- _lastGrounded = Time.time;
- }
- }
- private void Update()
- {
- Vector2 playerMovement = _playerInputs.Default.Movement.ReadValue<Vector2>();
- Vector3 velocity = _characterController.velocity;
- if (_isGrounded)
- {
- velocity = new Vector3(0, 0, playerMovement.x) * _moveSpeed;
- } else
- {
- _yVelocity -= _gravity;
- }
- velocity.y = _yVelocity;
- _characterController.Move(velocity * Time.deltaTime);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement