0
votes

I have some code that causes the box2d physics simulation to stutter forever after this code is called once. I ran a performance test on it and OSSpinLockLock has a lot of time spent on it. b2Island::Solve and some other box2d functions are causing this to take up so much time. I'm not really sure what is going on here. The effects of this seem to be worse on maps with more overlapping static bodies then maps with less overlapping static bodies. The code that causes the stutter is the following:

for (b2Body*b = currentWorld->GetBodyList(); b!=nil; b = b->GetNext()) {



    float distance = 0;
    float strength = 0;
    float force = 0;
    float angle = 0;

    CGPoint curPos = [Helper toPixels:b->GetWorldCenter()];

    distance = ccpDistance(selfPos, curPos);
    if (distance>maxDistance) {
        distance = maxDistance - 0.01;
    }

    //strength = (maxDistance - distance) / maxDistance;
    strength = (distance - maxDistance)/maxDistance;
    force = strength * maxForce;
    angle = atan2f(selfPos.y - curPos.y, selfPos.x - curPos.x);
    //b2Vec2 forceVec = [Helper toMeters:force];

    //CCLOG(@"strength = %f force = %f angle = %f distance = %f",strength,angle,force, distance);
    b->ApplyLinearImpulse(b2Vec2(cosf(angle) * force, sinf(angle) * force), b->GetPosition());
    BodyNode * bn = (BodyNode*)b->GetUserData();
    if ([bn isKindOfClass:[Soldier class]]) {
        ((Soldier*)bn).health-=abs(force*(damage * kRocketDamageFactor)); //used to be 50
    }
    if ([bn isKindOfClass:[BaseAI class]]) {
        ((BaseAI*)bn).health-=abs(force*(damage * kRocketDamageFactor));
    }
    if ([bn isKindOfClass:[BaseLevelObject class]]) {
        if (((BaseLevelObject*)bn).takesDamageFromBullets == YES) {
            ((BaseLevelObject*)bn).health-=abs(force*(damage * kRocketDamageFactor));
        }

    }

I suspect that the ApplyLinearImpulse part is what is causing the stutter because it is the only thing related to physics. I just commented out this whole loop and the stutter never came. But as soon as I exploded some other explosives with the same code, the stutter came. Do overlapping static b2body objects slow the physics simulation down?

1
Confirmed. It is the ApplyLinearImpulse function that is causing the jitter.Ben Trapani
I ran another performance test and am positive that the process that is related to the jitter is b2PairLessThan(b2Pair const&, b2Pair const&). This process doesn't even show up in the top 50 or so when the jitter isn't present. The code that is causing the jitter (the large sample above) is called from the BeginContact function of a b2ContactListener.Ben Trapani

1 Answers

0
votes

The issue was caused by the code giving all the bodies that were farther away than the max distance a small tap towards the explosion. I'm not really sure why this would cause the physics simulation to stutter, but adding a continue statement in place of distance = maxDistance - 0.01; solved the problem.