检查bool在至少x时间内是否为真?

时间:2018-03-17 02:00:16

标签: c# unity3d unityscript

目前我有一个光线投射设置,可以检查播放器是否接地并可以跳转。在某些情况下,这个地面检查可能是真的,但登陆动画还没有完成。出于这个原因,我想做一些事情,如果isGrounded是至少x秒/帧做的事情。如何实现这一检查?

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;
}

1 个答案:

答案 0 :(得分:1)

JumpCheck()功能和跳跃flag均为true时启动计时器。在计时器之前,将该标志设置为false,以便它不能再次跳转。在计时器结束时,再次将标志设置为true。有很多方法可以做到这一点。这只是其中之一。在下面的示例中,标志为readyToJumpAgain。默认值应为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;
}