Hello, I can't run and jump at the same time... I've been suffering for two days now, I can't figure out where the error is. Please help, any help would be appreciated.
using UnityEngine;
public class Movement : MonoBehaviour
{
[Header("Gravity")] [SerializeField] float gravity = 9.8f;
[SerializeField] float gravityMultiplier = 2;
[SerializeField] float jumpHeight = 3f;
private float _velocityY;
[Header("Movement")] [SerializeField] float speed = 4f;
[SerializeField] float rotationSmoothTime = 0.2f;
private CharacterController _controller;
private Camera _camera;
private float _currentAngle;
private float _currentAngleVelocity;
private void Awake()
{
_controller = GetComponent<CharacterController>();
_camera = Camera.main;
}
private void Update()
{
HandleMovement();
HandelGravityAndJump();
}
private void HandleMovement()
{
float horizontal = Input.GetAxisRaw("Horizontal");
float vertical = Input.GetAxisRaw("Vertical");
Vector3 movement = new Vector3(horizontal, 0f, vertical).normalized;
if (movement.magnitude >= 0.1f)
{
float targetAngle = Mathf.Atan2(movement.x, movement.z) * Mathf.Rad2Deg + _camera.transform.eulerAngles.y;
_currentAngle = Mathf.SmoothDampAngle(_currentAngle, targetAngle, ref _currentAngleVelocity, rotationSmoothTime);
transform.rotation = Quaternion.Euler(0f, _currentAngle, 0f);
Vector3 rotateMovement = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
_controller.Move(rotateMovement * (speed * Time.deltaTime));
}
}
private void HandelGravityAndJump()
{
if (_controller.isGrounded && Input.GetKeyDown(KeyCode.Space))
{
_velocityY = Mathf.Sqrt(jumpHeight * 2f * gravity);
}
_velocityY -= gravity * gravityMultiplier * Time.deltaTime;
_controller.Move(Vector3.up * (_velocityY * Time.deltaTime));
}
}