Bullet.cpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. //
  2. // Created by jovian on 18/07/17.
  3. //
  4. #include <iostream>
  5. #include "Bullet.h"
  6. #include "b2Angle.h"
  7. #define DEFAULT_TIME_LIFE 480
  8. Bullet::Bullet(const b2Vec2 &pos, b2World *physics, const b2Vec2 &dir, const b2Vec2 &speed, unsigned int camp)
  9. : Entity(BULLET, 0, physics),
  10. m_damageScale(0.015f), m_timeLife(DEFAULT_TIME_LIFE), m_camp(camp), m_aero(0.3f), m_dir(dir) {
  11. // Creation of physical body
  12. b2BodyDef bodyDef;
  13. bodyDef.type = b2_dynamicBody;
  14. bodyDef.position = pos;
  15. bodyDef.angle = b2Angle(dir);
  16. bodyDef.fixedRotation = false;
  17. bodyDef.bullet = true;
  18. bodyDef.angularDamping = 5.0f;
  19. m_body = physics->CreateBody(&bodyDef);
  20. // Creation of triangle shape
  21. b2Vec2 vertices[3];
  22. vertices[0].Set(-9.0f / DEFAULT_ZOOM, 10.0f / DEFAULT_ZOOM);
  23. vertices[1].Set(9.8f / DEFAULT_ZOOM, 0.0f);
  24. vertices[2].Set(-9.0f / DEFAULT_ZOOM, -10.0f / DEFAULT_ZOOM);
  25. b2PolygonShape shape;
  26. shape.Set(vertices, 3);
  27. // Definition of fixture
  28. b2FixtureDef fixtureDef;
  29. fixtureDef.shape = &shape;
  30. fixtureDef.density = 1.0f;
  31. fixtureDef.friction = 0.03f;
  32. fixtureDef.restitution = 0.1f;
  33. // Fixture filtering
  34. if (m_camp == 0)
  35. fixtureDef.filter.categoryBits = 0b0010;
  36. else if (m_camp == 1)
  37. fixtureDef.filter.categoryBits = 0b1000;
  38. fixtureDef.filter.maskBits = 0b1111;
  39. // Creation of fixture
  40. m_body->CreateFixture(&fixtureDef);
  41. // Initial propulsion
  42. m_body->SetLinearVelocity(speed);
  43. m_dir.Normalize();
  44. m_body->ApplyForceToCenter(10.0f * m_dir, true);
  45. // Appearance
  46. if (camp == 0)
  47. m_imgId = 12;
  48. else if (camp == 1)
  49. m_imgId = 14;
  50. // Link this bullet
  51. establishPhysicalLink();
  52. }
  53. void Bullet::update() {
  54. // Boost
  55. m_body->ApplyForceToCenter(m_aero * m_dir, true);
  56. // Existence
  57. if (m_timeLife == 0 || m_body->GetPosition().y > 100.0f)
  58. m_exist = false;
  59. else //if (!m_body->IsAwake())
  60. m_timeLife--;
  61. }
  62. int Bullet::getDamage() const {
  63. return (int) (m_damageScale * m_body->GetLinearVelocity().LengthSquared()) + 1;
  64. }