Bullet.cpp 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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, unsigned int camp)
  9. : Entity(BULLET, 0, physics),
  10. m_damageScale(0.015f), m_timeLife(DEFAULT_TIME_LIFE), m_camp(camp), m_aero(0.003f) {
  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(42.0f * dir);
  43. // Appearance
  44. if (camp == 0)
  45. m_imgId = 12;
  46. else if (camp == 1)
  47. m_imgId = 14;
  48. // Link this bullet
  49. establishPhysicalLink();
  50. }
  51. void Bullet::update() {
  52. // Aerodynamic
  53. b2Vec2 dir(m_body->GetLinearVelocity());
  54. const float speed(dir.Length());
  55. if (m_body->IsAwake() && speed > 0.0f) {
  56. dir = 1.0f / speed * dir;
  57. m_body->ApplyForce(-speed * speed * m_aero * dir, m_body->GetWorldPoint(b2Vec2(-0.2f, 0.0f)), true);
  58. }
  59. // Decrease CPU load when bullet is slower
  60. if (m_body->IsBullet() && speed < 7.75f && m_timeLife < DEFAULT_TIME_LIFE) {
  61. m_body->SetBullet(false);
  62. }
  63. // Existence
  64. if (m_timeLife == 0 || m_body->GetPosition().y > 100.0f)
  65. m_exist = false;
  66. else //if (!m_body->IsAwake())
  67. m_timeLife--;
  68. }
  69. int Bullet::getDamage() const {
  70. return (int) (m_damageScale * m_body->GetLinearVelocity().LengthSquared()) + 1;
  71. }