Enemy.cpp 2.1 KB

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