-(void)tick:(ccTime)deltaTime {
if(canShoot)
[self performPistol];
[self updatePositions:deltaTime];
[self collisionDetection];
}
-(void)updatePositions:(ccTime)deltaTime {
int32 velocityIterations = 8;
int32 positionIterations = 1;
world->Step(deltaTime, velocityIterations, positionIterations);
for(id object in _objectsToDelete) {
b2Body *body = (b2Body*)[object pointerValue];
[self removeChild:((CCSprite*)body->GetUserData()) cleanup:YES];
world->DestroyBody((b2Body*)[object pointerValue]);
}
[_objectsToDelete removeAllObjects];
}
-(void)collisionDetection {
for (b2Contact* c = world->GetContactList(); c; c = c->GetNext()) {
b2Body *a = c->GetFixtureA()->GetBody();
b2Body *b = c->GetFixtureB()->GetBody();
CCSprite *aSprite = (CCSprite*)a->GetUserData();
CCSprite *bSprite = (CCSprite*)b->GetUserData();
if([[aSprite class] isSubclassOfClass:[Bullet class]]) {
if([[bSprite class] isSubclassOfClass:[Zombie class]]) {
Zombie *myZombie = (Zombie*)bSprite;
myZombie.hp -= [(Bullet*)aSprite strength];
if(myZombie.hp <= 0) {
[_objectsToDelete addObject:[NSValue valueWithPointer:b]];
}
}
[_objectsToDelete addObject:[NSValue valueWithPointer:a]];
} else if([[bSprite class] isSubclassOfClass:[Bullet class]]) {
if([[aSprite class] isSubclassOfClass:[Zombie class]]) {
Zombie *myZombie = (Zombie*)aSprite;
myZombie.hp -= [(Bullet*)bSprite strength];
if(myZombie.hp <= 0) {
[_objectsToDelete addObject:[NSValue valueWithPointer:a]];
}
}
[_objectsToDelete addObject:[NSValue valueWithPointer:b]];
}
}
}
-(void)performPistol {
float degreeRadians = _myRotation*(M_PI/180.0);
CGPoint normalVector = ccp(cosf(degreeRadians),sinf(degreeRadians));
Bullet *bullet = [[Bullet alloc] initWithFile:@"bullet_line.png"];
bullet.strength = 1;
bullet.position = ccp(_myPosition.x+(normalVector.x*25.0),_myPosition.y+(normalVector.y*25.0));
bullet.rotation = _myRotation*(-1);
b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;
bodyDef.bullet = true;
bodyDef.position.Set(bullet.position.x/PTM_RATIO, bullet.position.y/PTM_RATIO);
bodyDef.userData = bullet;
b2Body *body = world->CreateBody(&bodyDef);
// Define another box shape for our dynamic body.
b2PolygonShape box;
box.SetAsBox(6.25/PTM_RATIO, 0.5/PTM_RATIO);
// Define the dynamic body fixture.
b2FixtureDef fixtureDef;
fixtureDef.shape = &box;
fixtureDef.density = 1.0f;
fixtureDef.friction = 0.3f;
fixtureDef.filter.categoryBits = MASK_PLAYER;
fixtureDef.filter.maskBits = MASK_ENEMY | MASK_WALL;
body->CreateFixture(&fixtureDef);
body->SetLinearVelocity(b2Vec2(normalVector.x*50.0,normalVector.y*50.0));
body->SetTransform(body->GetPosition(), CC_DEGREES_TO_RADIANS(-bullet.rotation));
[self addChild:bullet];
}
为什么CreateFixture()函数中存在错误。结束并不总是相同的有时一个断言错误有时是一个exc_bad_access?
感谢