AIAgent.cpp 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. #include "Base.h"
  2. #include "AIAgent.h"
  3. #include "Node.h"
  4. namespace gameplay
  5. {
  6. AIAgent::AIAgent()
  7. : _stateMachine(NULL), _node(NULL), _enabled(true), _listener(NULL), _next(NULL)
  8. {
  9. _stateMachine = new AIStateMachine(this);
  10. addScriptEvent("message", "<AIMessage>");
  11. }
  12. AIAgent::~AIAgent()
  13. {
  14. SAFE_DELETE(_stateMachine);
  15. }
  16. AIAgent* AIAgent::create()
  17. {
  18. return new AIAgent();
  19. }
  20. const char* AIAgent::getId() const
  21. {
  22. if (_node)
  23. return _node->getId();
  24. return "";
  25. }
  26. Node* AIAgent::getNode() const
  27. {
  28. return _node;
  29. }
  30. AIStateMachine* AIAgent::getStateMachine()
  31. {
  32. return _stateMachine;
  33. }
  34. bool AIAgent::isEnabled() const
  35. {
  36. return (_node && _enabled);
  37. }
  38. void AIAgent::setEnabled(bool enabled)
  39. {
  40. _enabled = enabled;
  41. }
  42. void AIAgent::setListener(Listener* listener)
  43. {
  44. _listener = listener;
  45. }
  46. void AIAgent::update(float elapsedTime)
  47. {
  48. _stateMachine->update(elapsedTime);
  49. }
  50. bool AIAgent::processMessage(AIMessage* message)
  51. {
  52. // Handle built-in message types.
  53. switch (message->_messageType)
  54. {
  55. case AIMessage::MESSAGE_TYPE_STATE_CHANGE:
  56. {
  57. // Change state message
  58. const char* stateId = message->getString(0);
  59. if (stateId)
  60. {
  61. AIState* state = _stateMachine->getState(stateId);
  62. if (state)
  63. _stateMachine->setStateInternal(state);
  64. }
  65. }
  66. break;
  67. }
  68. // Dispatch message to registered listener.
  69. if (_listener && _listener->messageReceived(message))
  70. return true;
  71. if (fireScriptEvent<bool>("message", message))
  72. return true;
  73. return false;
  74. }
  75. }