Can’t figure out where I’m going wrong on this one. If I set max jumps to 1, I get a double jump, and when I set it to 0, I get no jumps.
For some reason, on the initial jump, the value isn’t decreasing by 1.
I’ve tried a couple of other ways as well with no luck
public class PlayerMovement : MonoBehaviour
{
public float moveSpeed = 8f;
public float jumpForce = 20f;
public Transform groundCheck;
public LayerMask groundLayer;
public float coyoteTime = 0.2f;
public int maxJumps = 2;
private Rigidbody2D rb;
private bool isGrounded;
private float coyoteTimeCounter;
private int jumpCount;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
// horizontal movement
float moveInput = Input.GetAxis("Horizontal");
rb.velocity = new Vector2(moveInput * moveSpeed, rb.velocity.y);
// ground
isGrounded = Physics2D.OverlapCircle(groundCheck.position, 0.1f, groundLayer);
// Coyote Time
if (isGrounded)
{
coyoteTimeCounter = coyoteTime;
jumpCount = maxJumps;
}
else
{
coyoteTimeCounter -= Time.deltaTime;
}
// Handle Jumping
if (Input.GetButtonDown("Jump"))
{
if ((isGrounded || coyoteTimeCounter > 0f) && jumpCount > 0)
{
PerformJump();
}
else if (jumpCount > 0)
{
PerformJump();
}
}
Debug.Log("Jumps left: " + jumpCount);
}
void PerformJump()
{
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
jumpCount--;
coyoteTimeCounter = 0f;
}
}
New contributor
Marcus Hormann is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1