Question

So I have the following swept AABB collision detection algorithm working all fine and dandy (based on this article)

My question is how can I determine the collision normal, or in other words, the side of the box that aabb0 hit aabb1 on?

I've looked high and low on Google to no avail. I need the normal of the collision so I can determine how to 'slide' aabb0 after a collision. (aabb0 is the player's bounding box and aabb1 is a static block somewhere in the world).

aabb0 is the player's bounding box. d0 is the displacement of aabb0. aabb1 is a static block in the world. d1 is the displacement of aabb1 (always 0). u0 and u1 are the first and last collision times.

template<typename T>
intersect_type_t intersects(const aabb_t<T> aabb0, const T& d0, const aabb_t<T>& aabb1, const T& d1, float32_t& u0, float32_t& u1)
{
    auto v = glm::value_ptr((d1 - d0));
    auto amin = glm::value_ptr(aabb0.min);
    auto amax = glm::value_ptr(aabb0.max);
    auto bmin = glm::value_ptr(aabb1.min);
    auto bmax = glm::value_ptr(aabb1.max);
    vec3_t u_0(FLT_MAX);
    vec3_t u_1(FLT_MIN);

    if(intersects(aabb0, aabb1) != intersect_type_t::disjoint)
    {
        u0 = u1 = 0;
        return intersect_type_t::intersect;
    }

    for(size_t i=0; i < 3; ++i)
    {
        if(v[i] == 0)
        {
            u_0[i] = 0;
            u_1[i] = 1;
            continue;
        }

        if(amax[i] < bmin[i] && v[i] < 0)
            u_0[i] = (amax[i] - bmin[i]) / v[i];

        else if(bmax[i] < amin[i] && v[i] > 0)
            u_0[i] = (amin[i] - bmax[i]) / v[i];

        if(bmax[i] > amin[i] && v[i] < 0)
            u_1[i] = (amin[i] - bmax[i]) / v[i];

        else if(amax[i] > bmin[i] && v[i] > 0)
            u_1[i] = (amax[i] - bmin[i]) / v[i];
    }

    u0 = glm::compMax(u_0);
    u1 = glm::compMin(u_1);

    return u0 >= 0 && u1 <= 1 && u0 <= u1 ? intersect_type_t::intersect : intersect_type_t::disjoint;
}
Was it helpful?

Solution

Replaced my return function with the following:

auto result = u0 >= 0 && u1 <= 1 && u0 <= u1 ? intersect_type_t::intersect : intersect_type_t::disjoint;

if(normal != nullptr && result == intersect_type_t::intersect)
{
    auto normal_value_ptr = glm::value_ptr(*normal);
    for(size_t i = 0; i < 3; ++i)
    {
        if(u_0[i] == u0)
        {
            normal_value_ptr[i] = v[i] > 0 ? 1.f : -1.f;
            break;
        }
    }
}

return result;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top