diff --git a/src/Camera.h b/src/Camera.h index fb1d2dd..3dbaab5 100644 --- a/src/Camera.h +++ b/src/Camera.h @@ -4,6 +4,8 @@ #include #include +#include "World.h" + const float CAMERA_HEIGHT = 1.8f; const float GRAVITY = 18.6f; // Should be in m/s^2 but it doesn't really work out with 9.8 so we double it @@ -72,7 +74,7 @@ class Camera return v; } - void move(float time) // time passed in seconds since last move + void move(World* world, float time) // time passed in seconds since last move { bool in_air = this->position.y > 1; @@ -81,8 +83,47 @@ class Camera glm::vec3 velocity = this->forward_velocity + this->horizontal_velocity + this->vertical_velocity; - glm::vec3 movement = (velocity * time); - this->position += movement; + glm::vec3 position_delta = (velocity * time); + + glm::vec3 new_position = this->position + position_delta; + + // AABB Algorithm + glm::vec3 aabb_dims = glm::vec3(0.8f, 1.8f, 0.2f); + glm::vec3 aabb_half_dims = aabb_dims / 2.0f; + + for (int axis = 0; axis < 3; axis++) { + glm::vec3 target_position = this->position; + target_position[axis] += position_delta[axis]; + + glm::vec3 min = glm::floor(target_position - aabb_half_dims); + glm::vec3 max = glm::ceil(target_position + aabb_half_dims); + + bool collided = false; + for (int x = min.x; x < max.x; x++) { + for (int y = min.y; y < max.y; y++) { + for (int z = min.z; z < max.z; z++) { + glm::ivec3 calculated_position = glm::ivec3(x, y, z); + if (world->get_voxel(calculated_position).has_value()) { + collided = true; + std::cout << "Collided!!" << std::endl; + break; + } + } + if (collided) { + break; + } + } + if (collided) { + break; + } + } + + if (!collided) { + this->position[axis] = new_position[axis]; + } + } + + // this->position += movement; // Don't want to clip into the ground right if (this->position.y <= 1 && in_air) diff --git a/src/main.cpp b/src/main.cpp index 51846a9..d9cce3d 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -516,7 +516,7 @@ int main() { float time_since_last_move = end_time - move_time; if (time_since_last_move >= 0.017) { - camera.move(time_since_last_move); + camera.move(&world, time_since_last_move); move_time = end_time; }