Sphere AABB Collision Detection Where AABB is rotated

  c++, glm, math, opengl, physics

I’m trying to create a Sphere to AABB collision detection method using GLM, where the AABB model is rotated 25 degrees on the x-axis. I’ve modified the collision detection found near the bottom of https://learnopengl.com/In-Practice/2D-Game/Collisions/Collision-detection in order to attempt to take in an offset value as the AABB center to account for the rotation however the detection is still a little wonky. At some points of the model the sphere doesn’t touch and at other it’s goes directly through the cube. How would I properly detect collisions between a sphere and a rotated cube object?

bool Physics::check_collisionf(Cube* cube, Sphere* sphere)
{
    // Get Center of Sphere 
    glm::vec3 center(sphere->position + sphere->radius);

    // Get Calculate closest point on cube to the sphere after transformation
    glm::vec3 pos
    {
        sphere->position.x,
        (cube->position.y * cosf(cube->rotation_angle.x)) - (sphere->position.z * sinf(cube->rotation_angle.x)),
        (cube->position.y * sinf(cube->rotation_angle.x)) + (sphere->position.z * cosf(cube->rotation_angle.x))
    };

    // Calculate AABB info (center, half-extents)
    glm::vec3 aabb_half_extents(cube->size / 2.0f);
    glm::vec3 aabb_center(cube->position + pos + aabb_half_extents);

    // Calculate Difference vector between both centers
    glm::vec3 difference = center - aabb_center;
    glm::vec3 clamped = glm::clamp(difference, -aabb_half_extents, aabb_half_extents);

    // Attach Clamped Value to AABB to get the point closest to circle
    glm::vec3 closest = clamped + aabb_center;

    // Calculate difference between Sphere Center and Closest point on AABB
    difference = closest - center;

    // Comparison Value
    float comparison = sphere->radius;

    // Return If overlapping
    return glm::length(difference) <= comparison;
}

Source: Windows Questions C++

LEAVE A COMMENT