如何在FSM中创建状态之间的时间间隔
本文关键字:之间 时间 状态 创建 FSM | 更新日期: 2023-09-27 18:25:08
我想在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);
}
}
}
您需要使用Coroutines,并使用方法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;
}