Enemy.cpp 1.7 KB

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