I’m making a 2.5d game and the character can only go left and right. But I have an error, whenever I press the “D” key the Player goes back and gets stuck but if I release the “D” key the character goes back to the normal position. Here’s the code but there’s some errors like verticalVelocity here.
using System;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
private PlayerControls controls;
private CharacterController characterController;
public float walkSpeed;
public Vector3 movementDirection;
private Vector2 moveInput;
private Vector2 aimInput;
private void Awake()
{
controls = new PlayerControls();
controls.Character.Movement.performed += context => moveInput = context.ReadValue<Vector2>();
controls.Character.Movement.canceled += context => moveInput = Vector2.zero;
controls.Character.Aim.performed += context => aimInput = context.ReadValue<Vector2>();
controls.Character.Aim.canceled += context => aimInput = Vector2.zero;
}
private void Start()
{
characterController = GetComponent<CharacterController>();
}
private void Update()
{
ApplyMovement();
}
private void ApplyMovement()
{
movementDirection = new Vector3(moveInput.x, 0, moveInput.y);
ApplyGravity();
if (movementDirection.magnitude > 0)
{
characterController.Move(movementDirection * Time.deltaTime * walkSpeed);
}
}
private void ApplyGravity()
{
if (characterController.isGrounded == false)
{
verticalVelocity = verticalVelocity - 9.81f * Time.deltaTime;
movementDirection.y = verticalVelocity;
}
else
verticalVelocity = -.5f;
}
private void OnEnable()
{
controls.Enable();
}
private void OnDisable()
{
controls.Disable();
}
}
so can anyone help to fix these errors?