// 单状态状态机
public class SingleStateMachine
{
// Prev值保存上次操作值
// Curr值保存当前操作值
// 单状态机,不是true,就是false
private bool m_bPrev;
public bool Prev { get { return m_bPrev; } }
private bool m_bCurr;
public bool Curr
{
get
{
return m_bCurr;
}
set
{
ChgState(value);
}
}
private Action m_funcRunEnter = null;
private Action<float> m_funcRunUpdate = null;
private Action m_funcRunExit = null;
public SingleStateMachine(Action funcEnter, Action<float> funcUpdate, Action funcExit)
{
m_bPrev = false;
m_bCurr = false;
m_funcRunEnter = funcEnter;
m_funcRunUpdate = funcUpdate;
m_funcRunExit = funcExit;
}
public void ChgState(bool bNext)
{
if (m_bCurr == bNext)
{
// 保存操作值
m_bPrev = m_bCurr;
m_bCurr = bNext;
}
else
{
m_bPrev = m_bCurr;
m_bCurr = bNext;
if (bNext)
{
this.Enter();
}
else
{
this.Exit();
}
}
}
private void Enter()
{
if (m_funcRunEnter != null)
{
m_funcRunEnter();
}
}
public void Update(float delta)
{
if (Curr && m_funcRunUpdate != null)
{
m_funcRunUpdate(delta);
}
}
private void Exit()
{
if (m_funcRunExit != null)
{
m_funcRunExit();
}
}
}
今天把手上的事做完后,看了下状态机的代码,因为以前只会用,没有看状态机具体怎么实现的,这次看了之后有了更深的理解。
单状态机:singlemachine
状态机定义:
// 正在回城中状态
public SingleStateMachine RetreatingState { get; private set; }
初始化状态机:
RetreatingState = new SingleStateMachine(this.runRetreatingBegin, this.runRetreating, this.runRetreatingEnd);
在update中更新状态机:
// 回城状态处理
this.RetreatingState.Update(updateTime);//只有当前curr为true,才会执行this.runretreating
切换状态机:
//切换状态机
public void TroopRetreating(bool bRetreat = true)
{
RetreatingState.Curr = bRetreat;
}
游戏中回城部分用到了,只有没回城 已回城这种态,可以用bool 值表示为true false
回城单状态机初始化完成后,一旦改变curr变量的值,就会chgState:状态变化如下:
当前(curr)->下一个(next)
true->false
true->true
false->true
false->false
显然如果先后状态不一致,并且下一个状态是true,那么enter;先后状态不一致,下一个状态false,那么exit。