feat: player can jump with adjustable gravity
This commit is contained in:
@@ -1,5 +1,4 @@
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System;
|
||||
using UnityEngine;
|
||||
using UnityEngine.InputSystem;
|
||||
|
||||
@@ -8,20 +7,55 @@ public class PlayerMovement : MonoBehaviour
|
||||
private InputMaster _inputMaster;
|
||||
[SerializeField] private CharacterController controller;
|
||||
[SerializeField] private float speed;
|
||||
[SerializeField] private Transform groundCheck;
|
||||
private float _groundDistance = 0.4f;
|
||||
[SerializeField] private LayerMask groundMask;
|
||||
|
||||
private Vector2 _moveDirection;
|
||||
private Vector3 _velocity;
|
||||
private readonly float _gravity = -9.81f * 2f;
|
||||
private bool _isGrounded;
|
||||
|
||||
private float _jumpHeight = 3f;
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
controller = GetComponent<CharacterController>();
|
||||
_inputMaster = new InputMaster();
|
||||
_inputMaster.Player.Move.Enable();
|
||||
_inputMaster.Player.Jump.Enable();
|
||||
}
|
||||
|
||||
public void OnMove(InputAction.CallbackContext context)
|
||||
{
|
||||
_moveDirection = context.ReadValue<Vector2>();
|
||||
Debug.Log("direction: " + _moveDirection);
|
||||
private void Update()
|
||||
{
|
||||
_isGrounded = Physics.CheckSphere(groundCheck.position, _groundDistance, groundMask);
|
||||
if (_isGrounded && _velocity.y < 0)
|
||||
{
|
||||
_velocity.y = -2f; //force player on the ground
|
||||
}
|
||||
|
||||
_moveDirection = _inputMaster.Player.Move.ReadValue<Vector2>();
|
||||
Vector3 move = transform.right * _moveDirection.x + transform.forward * _moveDirection.y;
|
||||
controller.Move(move * (speed * Time.deltaTime));
|
||||
|
||||
_velocity.y += _gravity * Time.deltaTime;
|
||||
controller.Move(_velocity * Time.deltaTime); // multiply again because of m/s^2
|
||||
}
|
||||
|
||||
public void Jump(InputAction.CallbackContext context)
|
||||
{
|
||||
if (context.performed)
|
||||
{
|
||||
if (_isGrounded)
|
||||
{
|
||||
_velocity.y = (float)Math.Sqrt(_jumpHeight * -2f * _gravity);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void OnDisable()
|
||||
{
|
||||
_inputMaster.Player.Move.Disable();
|
||||
_inputMaster.Player.Jump.Disable();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user