AIComponent.cpp 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // ----------------------------------------------------------------
  2. // From Game Programming in C++ by Sanjay Madhav
  3. // Copyright (C) 2017 Sanjay Madhav. All rights reserved.
  4. //
  5. // Released under the BSD License
  6. // See LICENSE in root directory for full details.
  7. // ----------------------------------------------------------------
  8. #include "AIComponent.h"
  9. #include "Actor.h"
  10. #include "AIState.h"
  11. #include <SDL/SDL_log.h>
  12. AIComponent::AIComponent(class Actor* owner)
  13. :Component(owner)
  14. ,mCurrentState(nullptr)
  15. {
  16. }
  17. void AIComponent::Update(float deltaTime)
  18. {
  19. if (mCurrentState)
  20. {
  21. mCurrentState->Update(deltaTime);
  22. }
  23. }
  24. void AIComponent::ChangeState(const std::string& name)
  25. {
  26. // First exit the current state
  27. if (mCurrentState)
  28. {
  29. mCurrentState->OnExit();
  30. }
  31. // Try to find the new state from the map
  32. auto iter = mStateMap.find(name);
  33. if (iter != mStateMap.end())
  34. {
  35. mCurrentState = iter->second;
  36. // We're entering the new state
  37. mCurrentState->OnEnter();
  38. }
  39. else
  40. {
  41. SDL_Log("Could not find AIState %s in state map", name.c_str());
  42. mCurrentState = nullptr;
  43. }
  44. }
  45. void AIComponent::RegisterState(AIState* state)
  46. {
  47. mStateMap.emplace(state->GetName(), state);
  48. }