3
votes

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?

1
how do you synchronize sprite positions with their body's position? Do you step the Box2D world and apply body positions to sprites or do you move the sprites and apply sprite positions to the bodies?LearnCocos2D
@LearnCocos2D I move the sprites and apply their positions to the bodies.Sam Hertz

1 Answers

1
votes

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;
    }