繁体   English   中英

如何在FSM中的状态之间创建时间间隔

[英]How to create time intervals between states in an FSM

我想在FSM中的状态执行之间创建一个计时器间隔。

我现在所拥有的是非常基本的,因为我还是编程的新手。 如果您可以将所有可能的解决方案保持在基本水平左右,那就太好了。

public override void Execute()
{
    //Logic for Idle state
    if (dirRight)
        oFSM.transform.Translate(Vector2.right * speed * Time.deltaTime);
    else
        oFSM.transform.Translate(-Vector2.right * speed * Time.deltaTime);

    if (oFSM.transform.position.x >= 2.0f)
        dirRight = false;
    else if (oFSM.transform.position.x <= -2.0f)
        dirRight = true;
    //play animation

    //Transition out of Idle state
    //SUBJECT TO CHANGE
    float timer = 0f;
    timer += Time.time;
    if (timer >= 3f)
    {
        int rng = Random.Range(0, 5);
        if (rng >= 0 && rng <= 1)
        {
            timer = 0;
            oFSM.ChangeStateTo(FSM.States.AtkPatt1);
        }
        else if (rng >= 2 && rng <= 3)
        {
            timer = 0;
            oFSM.ChangeStateTo(FSM.States.AtkPatt2);
        }
        else if (rng >= 4 && rng <= 5)
        {
            timer = 0;
            oFSM.ChangeStateTo(FSM.States.AtkPatt3);
        }
    }
}

您需要使用协程 ,并使用WaitForSeconds方法。

然后,您可以执行以下操作:

private float timeToWait = 3f;
private bool keepExecuting = false;
private Coroutine executeCR;

public void CallerMethod()
{
    // If the Coroutine is != null, we will stop it.
    if(executeCR != null)
    {
        StopCoroutine(executeCR);
    }

    // Start Coroutine execution: 
    executeCR = StartCoroutine( ExecuteCR() );
}

public void StoperMethod()
{
    keepExecuting = false;
}

private IEnumerator ExecuteCR()
{
    keepExecuting = true;

    while (keepExecuting)
    {
        // do something
        yield return new WaitForSeconds(timeToWait);

        int rng = UnityEngine.Random.Range(0, 5);
        if (rng >= 0 && rng <= 1)
        {
            oFSM.ChangeStateTo(FSM.States.AtkPatt1);
        }
        else if (rng >= 2 && rng <= 3)
        {
            oFSM.ChangeStateTo(FSM.States.AtkPatt2);
        }
        else if (rng >= 4 && rng <= 5)
        {
            oFSM.ChangeStateTo(FSM.States.AtkPatt3);
        }

    }

    // All Coroutines should "return" (they use "yield") something
    yield return null;    
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM