我有一些代码会导致 box2d 物理模拟在此代码被调用一次后永远口吃。我对它进行了性能测试,OSSpinLockLock 花了很多时间。b2Island::Solve 和其他一些 box2d 函数导致它占用了这么多时间。我不太确定这里发生了什么。与静态物体重叠较少的地图相比,这种效果在静态物体重叠较多的地图上似乎更糟。导致卡顿的代码如下:
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));
}
}
我怀疑 ApplyLinearImpulse 部分是导致口吃的原因,因为它是唯一与物理相关的东西。我只是注释掉了整个循环并且口吃从来没有出现过。但是,当我用相同的代码引爆了其他一些炸药时,口吃就来了。重叠的静态 b2body 对象会减慢物理模拟吗?