Dashing Mechanic

Hello! I’ve been following a tutorial on youtube on how to script a dashing mechanic into my 2D platformer. I followed along with the guide and the youtuber made it so that you have to double tap to dash. I don’t want that. I want to make it so that you can tap the dash button once but don’t know how to do it. Please help!

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

public class DoubleJump : MonoBehaviour
{
   public float speed = 10f;
   public float jumpPower = 20f;
   public int extraJumps = 1;
   [SerializeField] LayerMask groundLayer;
   [SerializeField] Rigidbody2D rb;
   [SerializeField] Transform feet;

   int jumpCount = 0;
   bool isGrounded;
   float mx;
   float jumpCoolDown;

   public float dashDistance = 15f;
   bool isDashing;
   float tapTime;
   KeyCode lastKeyCode;

   private void Update()
   {
       mx = Input.GetAxisRaw("Horizontal");

       if (Input.GetButtonDown("Jump"))
       {
           Jump();
       }

// Dashing
       if (Input.GetKeyDown(KeyCode.X))
       {
           if (tapTime > Time.time && lastKeyCode == KeyCode.X)
           {
               StartCoroutine(Dash(1f));
           }
           else
           {
               tapTime = Time.time + 0.3f;
           }

           lastKeyCode = KeyCode.X;
       }

       CheckGrounded();
   }

   private void FixedUpdate()
   {
       if (!isDashing)
       rb.velocity = new Vector2(mx * speed, rb.velocity.y);
   }

   void Jump()
   {
       if (isGrounded || jumpCount < extraJumps)
       rb.velocity = new Vector2(rb.velocity.x, jumpPower);
       jumpCount++;
   }

   void CheckGrounded()
   {
       if (Physics2D.OverlapCircle(feet.position, 0.5f, groundLayer))
       {
           isGrounded = true;
           jumpCount = 0;
           jumpCoolDown = Time.time + 0.2f;
       }
       else if (Time.time < jumpCoolDown)
       {
           isGrounded = true;
       }
       else
       {
           isGrounded = false;
       }
   }

   IEnumerator Dash (float direction)
   {
       isDashing = true;
       rb.velocity = new Vector2(rb.velocity.x, 0f);
       rb.AddForce(new Vector2(dashDistance * direction, 0f), ForceMode2D.Impulse);
       float gravity = rb.gravityScale;
       rb.gravityScale = 0;
       yield return new WaitForSeconds(0.4f);
       isDashing = false;
       rb.gravityScale = gravity;
   }
}

Might work if you remove all the extra chuff inside from line 35 to line 46 and instead ONLY do line 38 when you press X. It’s worth a try.

1 Like

It worked thanks!

1 Like