RUEfxShake.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. #include "RUEfxShake.h"
  2. #include "cocos2d.h"
  3. USING_NS_CC;
  4. NS_RU_BEGIN
  5. // not really useful, but I like clean default constructors
  6. RUEfxShake::RUEfxShake() : m_strength_x(0), m_strength_y(0)
  7. {
  8. }
  9. RUEfxShake::~RUEfxShake()
  10. {
  11. }
  12. RUEfxShake* RUEfxShake::create(float d, float strength)
  13. {
  14. // call other construction method with twice the same strength
  15. return createWithStrength(d, strength, strength);
  16. }
  17. RUEfxShake *RUEfxShake::createWithStrength(float duration, float strength_x, float strength_y, int interval)
  18. {
  19. RUEfxShake *pRet = new RUEfxShake();
  20. if (pRet && pRet->initWithDuration(duration, strength_x, strength_y,interval))
  21. {
  22. pRet->autorelease();
  23. }
  24. else
  25. {
  26. CC_SAFE_DELETE(pRet);
  27. }
  28. return pRet;
  29. }
  30. bool RUEfxShake::initWithDuration(float duration, float strength_x, float strength_y, int interval)
  31. {
  32. if (ActionInterval::initWithDuration(duration))
  33. {
  34. m_strength_x = strength_x;
  35. m_strength_y = strength_y;
  36. m_curFrameCount = 0;
  37. m_interval = interval;
  38. m_accelEnable = true;
  39. return true;
  40. }
  41. return false;
  42. }
  43. // Helper function. I included it here so that you can compile the whole file it returns a random value between min and max included
  44. static float fgRangeRand( float min, float max )
  45. {
  46. float rnd = ((float)rand() / (float)RAND_MAX);
  47. return rnd * (max - min) + min;
  48. }
  49. void RUEfxShake::update(float dt)
  50. {
  51. if (m_curFrameCount % m_interval != 0)
  52. {
  53. m_curFrameCount++;
  54. return;
  55. }
  56. float scale = m_accelEnable ? dt : 1.0;
  57. float randx = fgRangeRand(-m_strength_x, m_strength_x ) * scale;
  58. float randy = fgRangeRand(-m_strength_y, m_strength_y ) * scale;
  59. // move the target to a shaked position
  60. if (_target)
  61. _target->setPosition(m_StartPosition + Vec2( randx, randy));
  62. m_curFrameCount++;
  63. // CCLOG("efx shake : %f %f %d",randx,randy,m_curFrameCount);
  64. }
  65. void RUEfxShake::startWithTarget(Node *pTarget)
  66. {
  67. ActionInterval::startWithTarget( pTarget );
  68. // save the initial position
  69. m_StartPosition=pTarget->getPosition();
  70. }
  71. void RUEfxShake::stop()
  72. {
  73. // Action is done, reset clip position
  74. if (this->getTarget())
  75. this->getTarget()->setPosition(m_StartPosition);
  76. ActionInterval::stop();
  77. }
  78. NS_RU_END