In this tutorial, you'll learn how to implement a double jump feature in your 2D Unity game. We’ll guide you through setting up the necessary components and writing a simple C# script to enable your character to jump twice before touching the ground. Perfect for beginners, this video covers everything from creating the player GameObject to testing and tweaking the jump mechanics to ensure smooth and responsive gameplay. Enhance your game with this easy-to-follow guide!
WATCH FULL TUTORIAL ON YOUTUBE
=========================================================
3 Unity Projects Only $70 - ON SALE!!!!
1. Water Sort 9000 Levels
2. Ball Sort Sort 9000 Levels
3. Sling Shot 250 Levels
Contact: unitycoderz2022@gmail.com
=========================================================
Script:
PlayerController.cs
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float moveSpeed = 5f;
public float jumpForce = 10f;
public int maxJumpCount = 2; // Maximum number of jumps (1 initial + 1 extra)
public Transform groundCheck; // Assign this in the Inspector
public float groundCheckRadius = 0.2f;
public LayerMask groundLayer;
private int jumpCount;
private bool isGrounded;
private Rigidbody2D rb;
void Start()
{
rb = GetComponent<Rigidbody2D>();
jumpCount = maxJumpCount;
}
private bool IsGrounded()
{
return Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, groundLayer);
}
void Update()
{
// Move the player
float moveInput = Input.GetAxis("Horizontal");
rb.velocity = new Vector2(moveInput * moveSpeed, rb.velocity.y);
// Check for jump
if (Input.GetButtonDown("Jump") && jumpCount > 0)
{
Jump();
}
// Check if the player is grounded
// You might want to use a more robust method (e.g., collision detection)
isGrounded = Mathf.Abs(rb.velocity.y) < 0.01f;
if (isGrounded)
{
jumpCount = maxJumpCount; // Reset the jump count when grounded
}
}
private void Jump()
{
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
jumpCount--;
}
}