#Dash script

1 messages · Page 1 of 1 (latest)

left oasis
#

I am having trouble setting up a dash script, everything is working but I want you to be able to dash 3 times before landing but the amount of times you can dash doesn't reset when you land.

#

using UnityEngine;

public class PlayerDash : MonoBehaviour
{
[Header("Dash Settings")]
public float dashDistance = 5f;
public float dashSpeed = 20f;
public int maxDashes = 3;
public float rayLength = 8f;
public LayerMask dashLayerMask; // Assign Ground + Button layers in Inspector

private int dashCount = 0;
private Rigidbody2D rb;
private bool isDashing = false;

private void Awake()
{
    rb = GetComponent<Rigidbody2D>();
}

private void Update()
{
    // Reset dash count when grounded
    if (IsGrounded())
        dashCount = 0;

    if (Input.GetKeyDown(KeyCode.K) && dashCount < maxDashes)
    {
        Vector2 dashDir = Vector2.zero;

        if (Input.GetKey(KeyCode.W)) dashDir = Vector2.up;
        else if (Input.GetKey(KeyCode.S)) dashDir = Vector2.down;
        else if (Input.GetAxisRaw("Horizontal") > 0) dashDir = Vector2.right;
        else if (Input.GetAxisRaw("Horizontal") < 0) dashDir = Vector2.left;

        if (dashDir != Vector2.zero)
            AttemptDash(dashDir);
    }
}

private void AttemptDash(Vector2 dir)
{
    RaycastHit2D hit = Physics2D.Raycast(transform.position, dir, rayLength, dashLayerMask);

    if (hit.collider != null)
    {
        if (hit.collider.CompareTag("Button"))
        {
            // Cancel dash, but activate button
            hit.collider.GetComponent<ButtonTrigger>()?.PressButton();
            return;
        }
        else if (hit.collider.CompareTag("Ground"))
        {
            Vector2 targetPos = hit.point - (dir * 0.5f); // stop slightly before ground
            StartCoroutine(DashRoutine(targetPos));
        }
    }
}
#

private System.Collections.IEnumerator DashRoutine(Vector2 targetPos)
{
isDashing = true;
dashCount++;

    Vector2 startPos = rb.position;
    float t = 0f;

    while (t < 1f)
    {
        t += Time.deltaTime * dashSpeed;
        rb.MovePosition(Vector2.Lerp(startPos, targetPos, t));
        yield return null;
    }

    isDashing = false;
}

private bool IsGrounded()
{
    // Simple grounded check (add proper ground check if you already have one)
    return Physics2D.Raycast(transform.position, Vector2.down, 0.1f, LayerMask.GetMask("Ground"));
}

}

#

(the dash script)

burnt gulch
#

!code
but also "dash doesn't reset when you land" means your raycast is not hitting anything. keep in mind if your character's pivot is the center then 0.1 units below its transform.position might not be the ground