Hi,
I wanted to upgrade jumps a little bit by adding the coyote time that let me jump for short period of time after touching the ground. Unfortunately I don’t know why there is still double jump available even though I made some bool to check if the player has jumped. Maybe you know what is wrong here:
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerMovement : MonoBehaviour
{
Rigidbody2D myRigidbody;
Vector2 moveInput;
Animator animator;
CapsuleCollider2D myCollider;
[SerializeField] float moveSpeed = 5f;
[SerializeField] float jumpHeight = 15f;
[SerializeField] float climbingSpeed = 5f;
[SerializeField] float coyoteTime = 0.2f;
bool isGrounded;
bool hasJumped;
float coyoteTimeCounter;
float myRigidbodyGravityAtStart;
void Start()
{
myCollider = GetComponent<CapsuleCollider2D>();
myRigidbody = GetComponent<Rigidbody2D>();
animator = GetComponent<Animator>();
myRigidbodyGravityAtStart = myRigidbody.gravityScale;
}
void Update()
{
CheckForGround();
Run();
FlipSprite();
ClimbLadder();
}
void OnMove(InputValue value)
{
moveInput = value.Get<Vector2>();
Debug.Log(moveInput);
}
void OnJump(InputValue value)
{
if (value.isPressed)
{
if (isGrounded)
{
Jump();
hasJumped = true;
}
else if (coyoteTimeCounter > 0 && !hasJumped)
{
Jump();
hasJumped = true;
}
}
}
void Jump()
{
myRigidbody.velocity += new Vector2(0f, jumpHeight);
}
void CheckForGround()
{
isGrounded = myCollider.IsTouchingLayers(LayerMask.GetMask("Ground"));
if (isGrounded)
{
coyoteTimeCounter = coyoteTime;
hasJumped = false;
}
else
{
coyoteTimeCounter -= Time.deltaTime;
}
}
void Run()
{
Vector2 playerVelocity = new Vector2(moveInput.x * moveSpeed, myRigidbody.velocity.y);
myRigidbody.velocity = playerVelocity;
}
void FlipSprite()
{
bool playerHasHorizontalSpeed = Mathf.Abs(myRigidbody.velocity.x) > Mathf.Epsilon;
if (playerHasHorizontalSpeed)
{
transform.localScale = new Vector2(Mathf.Sign(myRigidbody.velocity.x), 1f);
animator.SetBool("isRunning", true);
}
else
{
animator.SetBool("isRunning", false);
}
}
void ClimbLadder()
{
if (!myCollider.IsTouchingLayers(LayerMask.GetMask("Climbing")))
{
myRigidbody.gravityScale = myRigidbodyGravityAtStart;
animator.SetBool("isClimbing", false);
return;
}
Vector2 climbingVelocity = new Vector2(moveInput.x * moveSpeed, moveInput.y * climbingSpeed);
myRigidbody.velocity = climbingVelocity;
myRigidbody.gravityScale = 0f;
bool playerHasVerticalSpeed = Mathf.Abs(myRigidbody.velocity.y) > Mathf.Epsilon;
animator.SetBool("isClimbing", playerHasVerticalSpeed);
}
}