我寫了一個有限狀態機的模板,因為我要寫不同的FSM 1.狀態用枚舉來代替(便於調試) 2.要運行FSM,只需要setState和updateState(float delta_time)即可 3.用GetState來獲取當前狀態 4.許多轉換都基於定時,因此我實現了方法GetTimeInCurState() 5.執行具體的action在這些方法內BeginState EndState UpdateState [cpp] // (c) Francois Guibert, www.frozax.com (@Frozax) #pragma once template<typename T> class fgFSM { public: fgFSM() : _time_in_cur_state(0.0f), _cur_state(-1) { } virtual void BeginState( T state ) {} virtual void UpdateState( T state ) {} virtual void EndState( T state ) {} void SetState( T state ) { EndState( (T)_cur_state ); _cur_state = state; _time_in_cur_state = 0.0f; BeginState( (T)_cur_state ); } void UpdateFSM( float delta_time ) { if( _cur_state != -1 ) { _time_in_cur_state+=delta_time; UpdateState( (T)_cur_state ); } } float GetTimeInCurState() { return _time_in_cur_state; } T GetState() { return (T)_cur_state; } private: float _time_in_cur_state; int _cur_state; }; // (c) Francois Guibert, www.frozax.com (@Frozax) #pragma once template<typename T> class fgFSM { public: fgFSM() : _time_in_cur_state(0.0f), _cur_state(-1) { } virtual void BeginState( T state ) {} virtual void UpdateState( T state ) {} virtual void EndState( T state ) {} void SetState( T state ) { EndState( (T)_cur_state ); _cur_state = state; _time_in_cur_state = 0.0f; BeginState( (T)_cur_state ); } void UpdateFSM( float delta_time ) { if( _cur_state != -1 ) { _time_in_cur_state+=delta_time; UpdateState( (T)_cur_state ); } } float GetTimeInCurState() { return _time_in_cur_state; } T GetState() { return (T)_cur_state; } private: float _time_in_cur_state; int _cur_state; }; 用法: 先建立需要應用到的狀態枚舉,比如 [cpp] enum EState { STT_OFF = -1, // optional, -1 is the initial state of the fsm STT_WALK, STT_RUN, STT_STOP, STT_EAT }; enum EState { STT_OFF = -1, // optional, -1 is the initial state of the fsm STT_WALK, STT_RUN, STT_STOP, STT_EAT }; 然後繼承class fgFSM [cpp] class ObjectUsingFSM: public fgFSM<EState> { public: // ... void UpdateState( EState t ); void BeginState( EState t ); void EndState( EState t ); // ... }; class ObjectUsingFSM: public fgFSM<EState> { public: // ... void UpdateState( EState t ); void BeginState( EState t ); void EndState( EState t ); // ... }; 該機,結束語: 你可以在你的項目當中免費使用這些代碼,這是非常簡單又常用的,另外你可以在以後根據需要在在EndState()裡面加入GetPrviousState() GetNextState()等等。。。