World.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #include <cmath>
  2. #include "common/world/World.h"
  3. #include "utils/Logger.h"
  4. #include "utils/Random.h"
  5. World::World() : blocks(7, 7), dirty(true) {
  6. }
  7. void World::addEntity(Entity* e) {
  8. entities.add(e);
  9. }
  10. void World::removeEntity(Entity* e) {
  11. for(int i = 0; i < entities.getLength(); i++) {
  12. if(entities[i] == e) {
  13. entities.removeBySwap(i);
  14. return;
  15. }
  16. }
  17. }
  18. List<Box> World::getBoxes(const Box& box) const {
  19. int minX = floorf(box.getMin()[0]);
  20. int minY = floorf(box.getMin()[1]);
  21. int minZ = floorf(box.getMin()[2]);
  22. int maxX = floorf(box.getMax()[0]);
  23. int maxY = floorf(box.getMax()[1]);
  24. int maxZ = floorf(box.getMax()[2]);
  25. List<Box> boxes;
  26. for(int x = minX; x <= maxX; x++) {
  27. for(int y = minY; y <= maxY; y++) {
  28. for(int z = minZ; z <= maxZ; z++) {
  29. Block::addBoxes(blocks.get(x, y, z), boxes,
  30. Vector3(static_cast<float>(x),
  31. static_cast<float>(y),
  32. static_cast<float>(z)));
  33. }
  34. }
  35. }
  36. return boxes;
  37. }
  38. void World::tick() {
  39. for(Entity* e : entities) {
  40. e->tick();
  41. if(!e->skip) {
  42. Vector3 move = limitMove(*e, e->getVelocity());
  43. e->move(move);
  44. }
  45. }
  46. }
  47. Vector3 World::limitMove(const Entity& e, Vector3 move) const {
  48. Box box = e.getBox();
  49. List<Box> boxes = getBoxes(box.expand(move));
  50. if(boxes.getLength() == 0) {
  51. return move;
  52. }
  53. Vector3 realMove;
  54. constexpr float step = 0.05f;
  55. while(move[0] != 0.0f || move[1] != 0.0f || move[2] != 0.0f) {
  56. for(int i = 0; i < 3; i++) {
  57. Vector3 old = realMove;
  58. if(move[i] > step) {
  59. realMove[i] += step;
  60. move[i] -= step;
  61. } else if(move[i] < -step) {
  62. realMove[i] -= step;
  63. move[i] += step;
  64. } else if(move[i] != 0.0f) {
  65. realMove[i] += move[i];
  66. move[i] = 0.0f;
  67. }
  68. Box moved = box.offset(realMove);
  69. for(const Box& box : boxes) {
  70. if(box.collidesWith(moved)) {
  71. move[i] = 0.0f;
  72. realMove = old;
  73. break;
  74. }
  75. }
  76. }
  77. }
  78. return realMove;
  79. }