Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Box2D for Collision Detection Only

I am using Box2D for collision detection only. My code is similar to that in Ray Wenderlich's tutorial here.

I am encountering a problem with this method. Since the code bypasses the Box2D simulation, there is no collision response. Therefore, sprites can overlap. I am aware that Box2D collision APIs provide a unit normal vector to help resolve collisions. However, this vector conveys direction but not magnitude. Therefore, I cannot determine how far I should move overlapping sprites. Does anyone know how to use the Box2D collision APIs to manually resolve an overlap?

like image 783
Sam Hertz Avatar asked Jun 06 '26 05:06

Sam Hertz


1 Answers

I don't know iOS stuff but what you want to do is use is to extend b2ContactListener and override PreSolve.

void PreSolve(b2Contact* contact, const b2Manifold* oldManifold);

If you set contact->SetEnabled(false) you will have the collision but it will not be acted upon. Once you have the collision you can do something similar to the below.

const b2Manifold* manifold = contact->GetManifold();

    if (manifold->m_pointCount == 0)
    {
        return;
    }

    b2Fixture* fixtureA = contact->GetFixtureA();
    b2Fixture* fixtureB = contact->GetFixtureB();

    b2PointState state1[b2_maxManifoldPoints], state2[b2_maxManifoldPoints];
    b2GetPointStates(state1, state2, oldManifold, manifold);

    b2WorldManifold worldManifold;
    contact->GetWorldManifold(&worldManifold);

    for (int32 i = 0; i < manifold->m_pointCount && m_pointCount < k_maxContactPoints; ++i)
    {
        ContactPoint* cp = m_points + m_pointCount;
        cp->fixtureA = fixtureA;
        cp->fixtureB = fixtureB;
        cp->position = worldManifold.m_points[i];
        cp->normal = worldManifold.m_normal;
        cp->state = state2[i];
        ++m_pointCount;
    } 
like image 90
ClassicThunder Avatar answered Jun 09 '26 00:06

ClassicThunder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!