Rigidbody2D double jump

I am a new programmer and want to implement double jump in my movement script

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
private Rigidbody2D rb;
private BoxCollider2D coll;
private SpriteRenderer sprite;
private Animator anim;

[SerializeField] private LayerMask jumpableGround;

private float dirX = 0f;
[SerializeField] private float moveSpeed = 7f;
[SerializeField] private float jumpForce = 14f;

private enum MovementState { idle, running, jumping, falling }

[SerializeField] private AudioSource jumpSoundEffect;

// Start is called before the first frame update
private void Start()
{
rb = GetComponent();
coll = GetComponent();
sprite = GetComponent();
anim = GetComponent();
}

// Update is called once per frame
private void Update()
{
dirX = Input.GetAxisRaw(“Horizontal”);
rb.velocity = new Vector2(dirX * moveSpeed, rb.velocity.y);

if (Input.GetButtonDown(“Jump”) && IsGrounded())
{
jumpSoundEffect.Play();
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
}

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 (rb.velocity.y > .1f)
{
state = MovementState.jumping;
}
else if (rb.velocity.y < -.1f)
{
state = MovementState.falling;
}

anim.SetInteger(“state”, (int)state);
}

private bool IsGrounded()
{
return Physics2D.BoxCast(coll.bounds.center, coll.bounds.size, 0f, Vector2.down, .1f, jumpableGround);
}
}

The forums are not here to simpstateyou to say what you want and just dump code. If you have a problem then please clearly state what it is and what you’ve tried to rectify it. If you want help in implementing something specific then state what part you’re struggling with.

There’s loads of tutorials out there showing this very common feature too.

When posting code, don’t use plain text, please use code-tags . You can edit your post to include these too.

To add to what @MelvMay wrote. There are a multitude of tutorials out there for exactly what you are trying to do, so please use the internet to your advantage first before using the forums.

I recommend some basic programming tutorials as well, they can help you understand what your doing.

I learned to program in college, but that’s all out dated now and everything I learned and more can be found on the internet easily, all it takes is a simple google search.

Thank you I eventually figured it out on my own

1 Like