working on AABB collision

This commit is contained in:
JISAUAY 2025-11-17 14:38:51 -06:00
parent c5bc26b630
commit 0f31fe8656
2 changed files with 45 additions and 4 deletions

View File

@ -4,6 +4,8 @@
#include <glm/glm.hpp> #include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/matrix_transform.hpp>
#include "World.h"
const float CAMERA_HEIGHT = 1.8f; 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 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; 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; 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 velocity = this->forward_velocity + this->horizontal_velocity + this->vertical_velocity;
glm::vec3 movement = (velocity * time); glm::vec3 position_delta = (velocity * time);
this->position += movement;
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 // Don't want to clip into the ground right
if (this->position.y <= 1 && in_air) if (this->position.y <= 1 && in_air)

View File

@ -516,7 +516,7 @@ int main() {
float time_since_last_move = end_time - move_time; float time_since_last_move = end_time - move_time;
if (time_since_last_move >= 0.017) if (time_since_last_move >= 0.017)
{ {
camera.move(time_since_last_move); camera.move(&world, time_since_last_move);
move_time = end_time; move_time = end_time;
} }