So the problem I’m facing is like this:
I have a player controller that allows the player to move left, right and jump. However, whenever my player jumps, he keeps moving in a direction even though no directional key is pressed when he is mid-air. He keeps moving left or right until he falls on ground and then stops. I suspect it has something to do with grounded logic, but I can’t figure it out.
void FixedUpdate()
{
//Make player fall faster
if (rb.velocity.y < 0)
{
rb.velocity += Vector2.up * Physics2D.gravity.y * (fallMultiplier - 1f) * Time.deltaTime;
}
grounded = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, whatIsGround);
isFalling = !grounded && rb.velocity.y < 0f;
}
void Update()
{
//Set running speed according to stamina
if (stamina > 15f && stamina < 60f)
{
sprintMoveSpeed = decreasedRunMoveSpeed;
}
else if (stamina < 15f)
{
sprintMoveSpeed = moveSpeed;
}
//Run stamina
if (isSprinting)
{
if (stamina > 15f)
{
stamina = Mathf.Clamp(stamina - (staminaDecreasePerFrame * Time.deltaTime), 0.0f, maxStamina);
}
staminaRegenTimer = 0.0f;
}
else if (stamina < maxStamina)
{
if (staminaRegenTimer >= staminaTimeToRegen)
stamina = Mathf.Clamp(stamina + (staminaIncreasePerFrame * Time.deltaTime), 0.0f, maxStamina);
else
staminaRegenTimer += Time.deltaTime;
}
//Move right
if (Input.GetKey(KeyCode.D) || rightArrowHeld)
{
rb.velocity = new Vector2(isSprinting ? sprintMoveSpeed : moveSpeed, rb.velocity.y);
}
//Move left
if (Input.GetKey(KeyCode.A) || leftArrowHeld)
{
rb.velocity = new Vector2(isSprinting ? -sprintMoveSpeed : -moveSpeed, rb.velocity.y);
}
//Jump
if ((Input.GetKeyDown(KeyCode.Space) || upArrowHeld) && grounded && stamina > staminaDecreasePerFrame)
{
rb.velocity = new Vector2(rb.velocity.x, jumpHeight);
stamina -= staminaDecreasePerFrame;
}
//Run
if (Input.GetKey(KeyCode.LeftShift))
{
isSprinting = true;
}
else if (Input.GetKeyUp(KeyCode.LeftShift))
{
isSprinting = false;
}
//Flip sprite based on player movement direction
if (rb.velocity.x < 0)
{
sr.flipX = true;
}
else if (rb.velocity.x > 0)
{
sr.flipX = false;
}
}