I created a script that allows the player to double jump, which works like a charm.
The problem is if the player walks off a cliff, they will still be able to jump twice. But that isn't how double jump works, right?
Can someone tell me how to make it so that if the player falls down a cliff, they will be able to jump only once?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
private Rigidbody2D rb;
private Animator anim;
private float movementInputDirection;
public float movementSpeed = 10f;
public float jumpForce = 16f;
public int amountOfJumps = 1;
private int amountOfJumpsLeft;
private bool isFacingRight = true;
private bool isWalking;
private bool isGrounded;
private bool canJump;
public float groundCheckRadius;
public LayerMask whatIsGround;
public Transform groundCheck;
void Awake()
{
rb = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
}
void Start()
{
amountOfJumpsLeft = amountOfJumps;
}
void Update()
{
CheckInput();
CheckMovementDirection();
UpdateAnimations();
CheckIfCanJump();
}
private void FixedUpdate()
{
ApplyMovement();
CheckSurroundings();
}
private void CheckMovementDirection() //flips sprite
{
if (isFacingRight && movementInputDirection < 0)
{
Flip();
}
else if (!isFacingRight && movementInputDirection > 0)
{
Flip();
}
if(rb.velocity.x != 0)
{
isWalking = true;
}
else
{
isWalking = false;
}
}
private void UpdateAnimations()
{
anim.SetBool("IsWalking", isWalking);
}
private void CheckInput()
{
movementInputDirection = Input.GetAxisRaw("Horizontal");
if (Input.GetButtonDown("Jump"))
{
Jump();
}
}
private void ApplyMovement() //player movement
{
rb.velocity = new Vector2(movementSpeed * movementInputDirection, rb.velocity.y);
}
private void Flip()
{
isFacingRight = !isFacingRight;
transform.Rotate(0f, 180f, 0f);
}
private void Jump()
{
if (canJump)
{
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
amountOfJumpsLeft--;
}
}
private void CheckSurroundings()
{
isGrounded = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, whatIsGround);
}
private void CheckIfCanJump()
{
if (isGrounded && rb.velocity.y < 0.01)
{
amountOfJumpsLeft = amountOfJumps;
}
if (amountOfJumpsLeft <= 0)
{
canJump = false;
}
else
{
canJump = true;
}
}
private void OnDrawGizmos()
{
Gizmos.DrawWireSphere(groundCheck.position, groundCheckRadius);
}
}