Rocket.cpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. #include "Rocket.h"
  2. #include "res.h"
  3. #include "Game.h"
  4. #include "Enemy.h"
  5. Rocket::Rocket(const Vector2& dir): _dir(dir)
  6. {
  7. }
  8. void Rocket::_init()
  9. {
  10. //initialize rocket's sprite
  11. spSprite sp = new Sprite;
  12. sp->setResAnim(res::ui.getResAnim("rocket"));
  13. sp->setAnchor(Vector2(0.5f, 0.5f));
  14. sp->setScale(0);
  15. sp->addTween(Sprite::TweenScale(1.0f), 500);
  16. _view->addChild(sp);
  17. _view->setRotation(atan2f(_dir.y, _dir.x));
  18. }
  19. void Rocket::_update(const UpdateState& us)
  20. {
  21. //move rocket by it's direction each frame
  22. Vector2 pos = _view->getPosition();
  23. pos += _dir * (us.dt / 1000.0f) * 500.0f;
  24. _view->setPosition(pos);
  25. //find intersection with Enemies and explode them
  26. for (Game::units::iterator i = _game->_units.begin(); i != _game->_units.end(); ++i)
  27. {
  28. spUnit unit = *i;
  29. //list of units has everything, but we need only Enemies
  30. spEnemy enemy = dynamic_cast<Enemy*>(unit.get());
  31. if (!enemy)
  32. continue;
  33. Vector2 d = unit->getPosition() - pos;
  34. if (d.length() < 20)
  35. {
  36. //if rocket is too close to Enemy then try to explode it and explode rocket
  37. enemy->explode();
  38. explode();
  39. return;
  40. }
  41. }
  42. //if rocked out of bounds then explode it
  43. RectF bounds(0, 0, _game->getWidth(), _game->getHeight());
  44. if (!bounds.pointIn(pos))
  45. {
  46. explode();
  47. }
  48. }
  49. void Rocket::explode()
  50. {
  51. //we are dead
  52. //set this flag to true and it this rocket would be removed from units list in Game::doUpdate
  53. _dead = true;
  54. //create explode sprite
  55. spSprite anim = new Sprite;
  56. anim->attachTo(_game);
  57. anim->setBlendMode(blend_add);
  58. anim->setPosition(_view->getPosition());
  59. anim->setAnchor(Vector2(0.5f, 0.5f));
  60. //run tween with explosion animation
  61. spTween tween = anim->addTween(Sprite::TweenAnim(res::ui.getResAnim("explosion")), 1000);
  62. //auto detach sprite when tween is done
  63. tween->detachWhenDone();
  64. //hide rocket and then detach it
  65. tween = _view->addTween(Actor::TweenAlpha(0), 500);
  66. tween->detachWhenDone();
  67. }