Animator.cpp 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #include "Animator.h"
  2. #include <stdio.h>
  3. #define ANIMATOR WalrusRPG::Animator
  4. using namespace WalrusRPG;
  5. namespace
  6. {
  7. unsigned get_animation_duration(const WalrusRPG::Animation &anim)
  8. {
  9. unsigned duration = 0;
  10. for (unsigned index = 0; index < anim.stripe.size(); index++)
  11. {
  12. duration += anim.stripe[index].duration;
  13. }
  14. return duration;
  15. }
  16. unsigned find_frame(const WalrusRPG::Animation &anim, int frame_time)
  17. {
  18. if (frame_time >= anim.duration && !anim.looping)
  19. {
  20. // simple looping checking
  21. // Also, a flag to detect if the animation ended could be an option
  22. return anim.stripe[anim.stripe.size() - 1].frame;
  23. }
  24. frame_time %= anim.duration;
  25. unsigned index = 0;
  26. do
  27. {
  28. frame_time -= anim.stripe[index].duration;
  29. index++;
  30. if (index >= anim.stripe.size())
  31. {
  32. if (anim.looping)
  33. index = 0;
  34. else
  35. return anim.stripe[anim.stripe.size() - 1].frame;
  36. }
  37. } while (frame_time > 0);
  38. return anim.stripe[index].frame;
  39. }
  40. }
  41. ANIMATOR::Animator()
  42. {
  43. elapsed_time = 0;
  44. }
  45. unsigned ANIMATOR::add_animation(Animation anim)
  46. {
  47. animations.push_back(anim);
  48. unsigned index = animations.size()-1;
  49. animations[index] = anim;
  50. animations[index].duration = get_animation_duration(anim);
  51. return animations.size();
  52. }
  53. unsigned ANIMATOR::get_animation_frame(unsigned id)
  54. {
  55. if (animations[id].stripe.empty())
  56. return id;
  57. return find_frame(animations[id], elapsed_time);
  58. }
  59. void ANIMATOR::update(unsigned dt)
  60. {
  61. elapsed_time += dt;
  62. }