Quincy Norbert
Quincy Norbert

Reputation: 451

Check if bool is true for atleast x time?

Currently I have a raycast setup that checks if the player is grounded and can jump. In some cases this groundcheck can be true, but the landing animation has not yet finished. For this reason I would like to do something like if isGrounded is true for at least x seconds/frames do something. How would one achieve this check?

void JumpRun()
{
    if (JumpCheck())
    {
        float jumpVelocity = Mathf.Sqrt(-2 * gravity * jumpHeight);
        velocityY = jumpVelocity;
        anim.SetTrigger("JumpRun");
        canJump = Time.time + 0f; //Delay after jump input
    }
}

private bool JumpCheck()
{
    Debug.DrawRay(transform.position, Vector3.down * distanceForJump, Color.red);

    if (Physics.Raycast(transform.position, Vector3.down, distanceForJump))
        return true;

    return false;
}

Upvotes: 0

Views: 202

Answers (1)

Programmer
Programmer

Reputation: 125245

Start timer when JumpCheck() function and a jump flag are both true. Before the timer, set that flag to false so that it cannot jump again. At the end of the timer, set the flag to true again. There are just many ways to do this. This is just one of them. In the example below, the flag is readyToJumpAgain. The default value should be true.

bool readyToJumpAgain = true;

void JumpRun()
{
    if (JumpCheck() && readyToJumpAgain)
    {
        float jumpVelocity = Mathf.Sqrt(-2 * gravity * jumpHeight);
        velocityY = jumpVelocity;
        anim.SetTrigger("JumpRun");
        //Start a timer that waits for 4 seconds
        StartCoroutine(waitForAnimation(4f));
    }
}

private IEnumerator waitForAnimation(float time)
{
    readyToJumpAgain = false;
    //Wait for x seconds
    yield return new WaitForSecondsRealtime(time);
    //Ready to jump again
    readyToJumpAgain = true;
}

Upvotes: 1

Related Questions