State.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. function State(onEnter, onExit, onUpdate) {
  2. var tryGetFunction = function (func) {
  3. if (func != null) {
  4. return func;
  5. }
  6. else {
  7. return function () { };
  8. }
  9. }
  10. this.OnEnter = tryGetFunction(onEnter);
  11. this.OnExit = tryGetFunction(onExit);
  12. this.OnUpdate = tryGetFunction(onUpdate);
  13. }
  14. function StateMachine() {
  15. this.states = {};
  16. this.currentState = null;
  17. this.lastState = null;
  18. this.RegisterState = function (name, state) {
  19. this.states[name] = state;
  20. state.name = name;
  21. }
  22. this.GetState = function (name) {
  23. if (this.states[name] != null) {
  24. return this.states[name];
  25. }
  26. else {
  27. console.log("StateMachine::getState - this is not a state called [ " + name + " ]");
  28. }
  29. }
  30. this.SetStateByName = function (stateName) {
  31. var state = this.GetState(stateName);
  32. if (state) {
  33. this.SetState(state);
  34. }
  35. }
  36. this.SetState = function (state) {
  37. if (state != null) {
  38. if (state == this.currentState) {
  39. console.log("WARNING @ StateMachine::setCurrentState -" + "var state [ " + state.name + " ] is the same as current state" );
  40. return;
  41. }
  42. this.lastState = this.currentState;
  43. this.currentState = state;
  44. if (this.lastState) {
  45. this.lastState.OnExit();
  46. }
  47. this.currentState.OnEnter();
  48. }
  49. else {
  50. console.log( "ERROR @ StateMachine::setCurrentState - " + " var [state] is not a class type of State" );
  51. }
  52. }
  53. }
  54. var SM = new StateMachine();