Actor.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  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::ProcessInput(const uint8_t* keyState)
  50. {
  51. if (mState == EActive)
  52. {
  53. // First process input for components
  54. for (auto comp : mComponents)
  55. {
  56. comp->ProcessInput(keyState);
  57. }
  58. ActorInput(keyState);
  59. }
  60. }
  61. void Actor::ActorInput(const uint8_t* keyState)
  62. {
  63. }
  64. void Actor::ComputeWorldTransform()
  65. {
  66. mWorldTransform = Matrix4::CreateScale(mScale);
  67. mWorldTransform *= Matrix4::CreateRotationZ(mRotation);
  68. mWorldTransform *= Matrix4::CreateTranslation(Vector3(mPosition.x, mPosition.y, 0.0f));
  69. }
  70. void Actor::AddComponent(Component* component)
  71. {
  72. // Find the insertion point in the sorted vector
  73. // (The first element with a order higher than me)
  74. int myOrder = component->GetUpdateOrder();
  75. auto iter = mComponents.begin();
  76. for (;
  77. iter != mComponents.end();
  78. ++iter)
  79. {
  80. if (myOrder < (*iter)->GetUpdateOrder())
  81. {
  82. break;
  83. }
  84. }
  85. // Inserts element before position of iterator
  86. mComponents.insert(iter, component);
  87. }
  88. void Actor::RemoveComponent(Component* component)
  89. {
  90. auto iter = std::find(mComponents.begin(), mComponents.end(), component);
  91. if (iter != mComponents.end())
  92. {
  93. mComponents.erase(iter);
  94. }
  95. }