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;
- [SerializeField]
- private bool _isGrounded = false;
- private CharacterController _characterController;
- private PlayerInputs _playerInputs;
- 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;
- // _playerInputs.Default.Interact.performed += Interact_performed;
- }
- private void Jump_performed(UnityEngine.InputSystem.InputAction.CallbackContext obj)
- {
- if (_isGrounded)
- {
- Vector3 velocity = _characterController.velocity;
- velocity.y += _jumpHeight;
- _characterController.Move(velocity * Time.deltaTime);
- }
- }
- 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;
- }
- 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
- {
- velocity.y -= _gravity;
- }
- transform.Translate(velocity);
- _characterController.Move(velocity * Time.deltaTime);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement