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