dash 2 times

I want the player to be able to dash twice, first one is a invulnerable dash and second is a normal dash.
 avatar
unknown
plain_text
10 days ago
1.6 kB
0
Indexable
public class PlayerController : MonoBehaviour
{
    public float dashSpeed = 20f;
    public float dashTime = 0.2f;
    public float dashCooldown = 1f;
    private bool canDash = true;
    private bool isDashing = false;
    private int dashCount = 0;
    public bool isInvulnerable = false;

    private Rigidbody2D rb;
    private SpriteRenderer spriteRenderer;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        spriteRenderer = GetComponent<SpriteRenderer>();
    }

    void Update()
    {
        HandleDash();
    }

    void HandleDash()
    {
        if (Input.GetKeyDown(KeyCode.LeftShift) && canDash)
        {
            StartCoroutine(Dash());
        }
    }

    IEnumerator Dash()
    {
        isDashing = true;
        dashCount++;

        if (dashCount == 1)
        {
            isInvulnerable = true;
            spriteRenderer.color = Color.red;
        }
        else
        {
            isInvulnerable = false;
            spriteRenderer.color = Color.white;
        }

        Vector2 dashDirection = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical")).normalized;
        rb.velocity = dashDirection * dashSpeed;

        yield return new WaitForSeconds(dashTime);

        rb.velocity = Vector2.zero;
        isDashing = false;

        if (dashCount >= 2)
        {
            canDash = false;
            dashCount = 0;
            yield return new WaitForSeconds(dashCooldown);
            canDash = true;
        }
    }
}
Leave a Comment