Enemy.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. #define _USE_MATH_DEFINES
  2. #include <cmath>
  3. #include "Enemy.h"
  4. #include "Model.h"
  5. #include <iostream>
  6. Enemy::Enemy(const std::string &fileName,
  7. const std::string &fileMusic,
  8. float damage,
  9. float health,
  10. const Vec3f &position,
  11. const Vec3f &rotation,
  12. const float &scale)
  13. {
  14. model = Model::load(fileName);
  15. this->position = position;
  16. this->rotation = rotation;
  17. this->scale = scale;
  18. this->canCollide = true;
  19. target = position;
  20. speed = 1;
  21. radius = 10;
  22. xp = health;
  23. this->health = health;
  24. this->damage = damage;
  25. hasTarget = false;
  26. hit_sound_id = CrystalPoint::GetSoundSystem().LoadSound(fileMusic.c_str(), false);
  27. music = CrystalPoint::GetSoundSystem().GetSound(hit_sound_id);
  28. attack = false;
  29. }
  30. Enemy::~Enemy()
  31. {
  32. music->Stop();
  33. CrystalPoint::GetSoundSystem().UnloadSound(hit_sound_id);
  34. if (model)
  35. Model::unload(model);
  36. }
  37. void Enemy::draw()
  38. {
  39. Entity::draw();
  40. glPushMatrix();
  41. glTranslatef(position.x, position.y, position.z);
  42. glBegin(GL_LINE_LOOP);
  43. for (int i = 0; i < 360; i++)
  44. {
  45. //convert degrees into radians
  46. float degInRad = i*(M_PI / 180.0);
  47. glVertex3f(cos(degInRad)*radius, 1*scale,sin(degInRad)*radius);
  48. }
  49. glEnd();
  50. glPopMatrix();
  51. }
  52. void Enemy::inEyeSight(Vec3f & TargetPosition)
  53. {
  54. if (position.Distance(TargetPosition) <= radius)
  55. {
  56. hasTarget = true;
  57. target = TargetPosition;
  58. }
  59. else
  60. hasTarget = false;
  61. }
  62. void Enemy::collide(const Entity * entity)
  63. {
  64. Vec3f difference = position - entity->position; //zou misschien omgedraait moeten worden
  65. difference.y = 0;
  66. difference.Normalize();
  67. difference = difference * (entity->model->radius + 0.01f);
  68. position.x = difference.x + entity->position.x;
  69. position.z = difference.z + entity->position.z;
  70. }
  71. void Enemy::update(float delta)
  72. {
  73. music->SetPos(position, Vec3f());
  74. if (hasTarget)
  75. {
  76. if (music->IsPlaying() == false)
  77. {
  78. music->Play();
  79. }
  80. //just 2d walking
  81. float dx, dz, length;
  82. dx = target.x - position.x;
  83. dz = target.z - position.z;
  84. length = sqrt(dx*dx + dz*dz);
  85. if (length > 1)
  86. {
  87. attack = false;
  88. dx /= length;
  89. dz /= length;
  90. dx *= speed*delta;
  91. dz *= speed*delta;
  92. position.x += dx;
  93. position.z += dz;
  94. }
  95. else
  96. {
  97. attack = true;
  98. }
  99. rotation.y = atan2f(dx, dz) * 180 / M_PI;
  100. }
  101. }