I'm an absolute beginner in Unity and C# and I'm having some issues inserting a double jump on my Unity 2D Project. My question is: How can I be able to add a double jump on this code? I tried to follow a lot of tutorials on internet, but I wasn't successful in any of the tutorials. This code I'm using right now is working normally, but I need to add the double jump function on the game. Here's the code I'm using, I really need some help.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
private Rigidbody2D rigidbody;
private BoxCollider2D collider;
private SpriteRenderer sprite;
private Animator animator;
[SerializeField] private LayerMask jumpableGround;
private float dirX = 0f;
[SerializeField]private float PlayerMovementSpeed = 7f;
[SerializeField]private float PlayerJumpSpeed = 8f;
private enum MovementState { idle, running, jumping, falling }
// Start is called before the first frame update
private void Start()
{
rigidbody = GetComponent<Rigidbody2D>();
collider = GetComponent<BoxCollider2D>();
sprite = GetComponent<SpriteRenderer>();
animator = GetComponent<Animator>();
}
// Update is called once per frame
private void Update()
{
dirX = Input.GetAxisRaw("Horizontal");
rigidbody.velocity = new Vector2(dirX * PlayerMovementSpeed, rigidbody.velocity.y);
if (Input.GetButtonDown("Jump") && IsGrounded())
{
GetComponent<Rigidbody2D>().velocity = new Vector2(0, PlayerJumpSpeed);
}
UpdateAnimationState();
}
private void UpdateAnimationState()
{
MovementState state;
if (dirX > 0f)
{
state = MovementState.running;
sprite.flipX = false;
}
else if (dirX < 0f)
{
state = MovementState.running;
sprite.flipX = true;
}
else
{
state = MovementState.idle;
}
if (rigidbody.velocity.y > .1f)
{
state = MovementState.jumping;
}
else if (rigidbody.velocity.y < -.1f)
{
state = MovementState.falling;
}
animator.SetInteger("state", (int)state);
}
private bool IsGrounded()
{
return Physics2D.BoxCast(collider.bounds.center, collider.bounds.size, 0f, Vector2.down, .1f, jumpableGround);
}
}