World.cpp 1.8 KB

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