Actor.cpp 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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 "Actor.h"
  9. #include "Game.h"
  10. #include "Component.h"
  11. #include <algorithm>
  12. Actor::Actor(Game* game)
  13. :mState(EActive)
  14. , mPosition(Vector2::Zero)
  15. , mScale(1.0f)
  16. , mRotation(0.0f)
  17. , mGame(game)
  18. {
  19. mGame->AddActor(this);
  20. }
  21. Actor::~Actor()
  22. {
  23. mGame->RemoveActor(this);
  24. // Need to delete components
  25. // Because ~Component calls RemoveComponent, need a different style loop
  26. while (!mComponents.empty())
  27. {
  28. delete mComponents.back();
  29. }
  30. }
  31. void Actor::Update(float deltaTime)
  32. {
  33. if (mState == EActive)
  34. {
  35. UpdateComponents(deltaTime);
  36. UpdateActor(deltaTime);
  37. }
  38. }
  39. void Actor::UpdateComponents(float deltaTime)
  40. {
  41. for (auto comp : mComponents)
  42. {
  43. comp->Update(deltaTime);
  44. }
  45. }
  46. void Actor::UpdateActor(float deltaTime)
  47. {
  48. }
  49. void Actor::AddComponent(Component* component)
  50. {
  51. // Find the insertion point in the sorted vector
  52. // (The first element with a order higher than me)
  53. int myOrder = component->GetUpdateOrder();
  54. auto iter = mComponents.begin();
  55. for (;
  56. iter != mComponents.end();
  57. ++iter)
  58. {
  59. if (myOrder < (*iter)->GetUpdateOrder())
  60. {
  61. break;
  62. }
  63. }
  64. // Inserts element before position of iterator
  65. mComponents.insert(iter, component);
  66. }
  67. void Actor::RemoveComponent(Component* component)
  68. {
  69. auto iter = std::find(mComponents.begin(), mComponents.end(), component);
  70. if (iter != mComponents.end())
  71. {
  72. mComponents.erase(iter);
  73. }
  74. }