World.cpp 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #include "World.h"
  2. #include <GL/freeglut.h>
  3. #include "Entity.h"
  4. #include "LevelObject.h"
  5. #include "json.h"
  6. #include <fstream>
  7. World::World() : player(Player::getInstance())
  8. {
  9. json::Value v = json::readJson(std::ifstream("worlds/world1.json"));
  10. player.position.x = v["player"]["startposition"][0];
  11. player.position.y = v["player"]["startposition"][1];
  12. player.position.z = v["player"]["startposition"][2];
  13. for (auto object : v["objects"])
  14. {
  15. bool hasCollision = true;
  16. if (!object["collide"].isNull())
  17. hasCollision = object["collide"].asBool();
  18. Vec3f rotation(0, 0, 0);
  19. if(!object["rot"].isNull())
  20. rotation = Vec3f(object["rot"][0], object["rot"][1], object["rot"][2]);
  21. float scale = 1;
  22. if (!object["scale"].isNull())
  23. scale = object["scale"].asFloat();
  24. Vec3f position(object["pos"][0], object["pos"][1], object["pos"][2]);
  25. entities.push_back(new LevelObject(object["file"], position, rotation, scale, hasCollision));
  26. }
  27. }
  28. World::~World()
  29. {
  30. }
  31. void World::draw()
  32. {
  33. player.setCamera();
  34. float lightPosition[4] = { 0, 2, 1, 0 };
  35. glLightfv(GL_LIGHT0, GL_POSITION, lightPosition);
  36. float lightAmbient[4] = { 0.5, 0.5, 0.5, 1 };
  37. glLightfv(GL_LIGHT0, GL_AMBIENT, lightAmbient);
  38. glColor3f(0.5f, 0.9f, 0.5f);
  39. glNormal3f(0, 1, 0);
  40. glBegin(GL_QUADS);
  41. glVertex3f(-50, 0, -50);
  42. glVertex3f(-50, 0, 50);
  43. glVertex3f(50, 0, 50);
  44. glVertex3f(50, 0, -50);
  45. glEnd();
  46. for (auto e : entities)
  47. e->draw();
  48. }
  49. void World::update(float elapsedTime)
  50. {
  51. for (auto e : entities)
  52. e->update(elapsedTime);
  53. }
  54. bool World::isPlayerPositionValid()
  55. {
  56. for (auto e : entities)
  57. {
  58. if (e->canCollide && e->inObject(player.position))
  59. return false;
  60. }
  61. return true;
  62. }