Dash.cs 2.32 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
using System.Collections;
using System.Collections.Generic;
using UnityEngine;


// Sets dash velocity and smoothly decelerates to a minimum velocity

public class Dash : AbstractBehavior {

    private float lastDash;
    public float coolDown = 1f;
    public float dashforce = 5;
    public float holdTime = 0.4f;
    public float minVelocity = 0.5f;
    private bool _isDashing = false;
    private Transform dashMeter;

    // Call to check if currently dashing
    public bool isDashing
    {
        get { return _isDashing; }
        private set
        {
            _isDashing = value;
        }
    }

    void Start() {
Ashley's avatar
Ashley committed
29
        //dashMeter = GameObject.FindGameObjectWithTag("DashMeter").transform;
30 31 32
    }

    // Should be called every frame
33 34 35 36 37
    public void DashCheck() {
        // Button pressed, not in cooldown, and not on wall
        if (inputState.GetButtonValue(inputButtons[0]) && Time.time > lastDash && !collisionState.onWall) {
            StartCoroutine(DoDash());
        }
38 39 40 41 42 43 44 45 46 47

        UpdateUI();
    }

    void UpdateUI() {
		float progress = 1 - ((lastDash - Time.time)/coolDown);
        dashMeter.localScale = new Vector2(Mathf.Clamp01(progress), dashMeter.localScale.y);
    }

    // Dash
48 49 50
    IEnumerator DoDash() {
        // Cooldown
        lastDash = Time.time + coolDown;
51 52
        // Is dashing
        isDashing = true;
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
        // Set initial velocity
        body.velocity = transform.right * dashforce;
        // Disable gravity
        float initialGrav = body.gravityScale;
        body.gravityScale = 0;

        // Decelerate
        for (float i = 0; i < holdTime; i += Time.deltaTime) {
            // Calculate velocity
            Vector2 targetVel = (transform.right * dashforce) * (1 - (i / holdTime));

            if(body.velocity.magnitude < minVelocity || collisionState.onWall) {
                // Velocity is low enough or collision with wall
                break;
            }

            // Apply velocity
            body.velocity = targetVel;
            // Wait
            yield return new WaitForEndOfFrame();
        }

        // Restore gravity
        body.gravityScale = initialGrav;
77 78 79 80 81 82 83 84
        // Is not dashing
        isDashing = false;
    }

	public void DashIgnoringCooldown() {
		StartCoroutine(DoDash());
	}
}