gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 21:53:17 26 4
gpt4 key购买 nike

我想在 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;
}

关于c# - 如何在 FSM 中创建状态之间的时间间隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34021440/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com