I am working on a game in which the user can control the gravity of the player. I want to add a cooldown to the Gravity Inversion ability. It should be so that once the user inverts the gravity, the timer will start, and once it reaches the limit, the ability will be disabled and the cooldown will be started. I can’t get the disabling and the reenabling part correctly.
Here is my current code:-
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class InvertGravity : MonoBehaviour
{
Rigidbody2D rb;
public bool GravityInverted = false; // This will check whether the gravity is inverted or not
// private int inverseGravTimer;
public int inverseGravLimit = 5;
public float cooldownTime = 10f;
// private float cooldownTimer = 0f;
public float waitingTime = 3f;
// private bool cooldownStarted = false;
public bool inversionInput;
// IEnumerator abilityCooldownTimer;
// private float nextUse = 3f;
public float inversionRate = 5f;
private bool AbilityIsReady;
public float abilityUseLimit;
public float cooldownLimit;
public void Start()
{
rb = GetComponent<Rigidbody2D>();
AbilityIsReady = true;
}
// Update is called once per frame
public void Update()
{
if (AbilityIsReady)
{
if (Input.GetKeyDown(KeyCode.LeftShift)) // Starts Gravity Inversion
{
FlipGravity();
StartCoroutine("AbilityUseTimer");
}
else if (Input.GetKeyUp(KeyCode.LeftShift)) // Stops Gravity Inversion
{
NormalizeGravity();
}
}
else if (!AbilityIsReady)
{
NormalizeGravity();
StartCoroutine("AbilityCooldownTimer");
}
}
public void NormalizeGravity()
{
GravityInverted = false;
FindObjectOfType<AudioManager>().PlaySound("NormalizeGravity");
rb.gravityScale = 1;
transform.Rotate(0f, 180f, 180f);
}
public void FlipGravity()
{
GravityInverted = true;
FindObjectOfType<AudioManager>().PlaySound("InvertGravity");
rb.gravityScale = -1;
transform.Rotate(0f, 180f, 180f);
}
IEnumerator AbilityUseTimer()
{
yield return new WaitForSeconds(abilityUseLimit);
AbilityIsReady = false;
}
IEnumerator AbilityCooldownTimer()
{
yield return new WaitForSeconds(cooldownLimit);
AbilityIsReady = true;
}