stamina_system.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #include "stamina_system.h"
  2. #include "../core/component.h"
  3. #include "../core/world.h"
  4. #include "../units/spawn_type.h"
  5. namespace Game::Systems {
  6. namespace {
  7. constexpr float kMinMovementSpeedSq = 0.01F;
  8. [[nodiscard]] inline auto is_unit_moving(
  9. const Engine::Core::MovementComponent *movement) noexcept -> bool {
  10. if (movement == nullptr) {
  11. return false;
  12. }
  13. const float speed_sq =
  14. movement->vx * movement->vx + movement->vz * movement->vz;
  15. return speed_sq > kMinMovementSpeedSq;
  16. }
  17. } // namespace
  18. void StaminaSystem::update(Engine::Core::World *world, float delta_time) {
  19. if (world == nullptr) {
  20. return;
  21. }
  22. for (auto *entity :
  23. world->get_entities_with<Engine::Core::StaminaComponent>()) {
  24. auto *stamina = entity->get_component<Engine::Core::StaminaComponent>();
  25. if (stamina == nullptr) {
  26. continue;
  27. }
  28. const auto *unit = entity->get_component<Engine::Core::UnitComponent>();
  29. if (unit == nullptr || unit->health <= 0) {
  30. stamina->is_running = false;
  31. continue;
  32. }
  33. if (!Game::Units::can_use_run_mode(unit->spawn_type)) {
  34. stamina->is_running = false;
  35. stamina->run_requested = false;
  36. continue;
  37. }
  38. const auto *movement =
  39. entity->get_component<Engine::Core::MovementComponent>();
  40. const bool is_moving = is_unit_moving(movement);
  41. if (stamina->run_requested && is_moving) {
  42. if (!stamina->is_running && stamina->can_start_running()) {
  43. stamina->is_running = true;
  44. }
  45. if (stamina->is_running) {
  46. stamina->deplete(delta_time);
  47. if (!stamina->has_stamina()) {
  48. stamina->is_running = false;
  49. }
  50. }
  51. } else {
  52. stamina->is_running = false;
  53. stamina->regenerate(delta_time);
  54. }
  55. }
  56. }
  57. } // namespace Game::Systems