我有一张精灵表,其中有四个图像(bat1,bat2,bat3.bat4),在Image中有一个人拿着蝙蝠,当所有图像在动画中组合时,它看起来像打棒球。 下面是我用来添加精灵表的代码。
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"baseball.plist"];
spriteSheet = [CCSpriteBatchNode batchNodeWithFile:@"baseball.plist"];
[self addChild:spriteSheet];
background = [CCSprite spriteWithSpriteFrameName:@"bat4.png"];
background.position = ccp(220, 185);
background.tag = 10;
[self addChild:background];
for(int i = 1; i < 5; i++) {
[walkAnimFrames addObject:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:[NSString stringWithFormat:@"bat%d.png", i]]];
}
CCAnimation * walkAnim = [CCAnimation animationWithSpriteFrames:walkAnimFrames delay:5.0f];
self.walkAction = [CCRepeatForever actionWithAction:[CCAnimate actionWithAnimation:walkAnim]];
[background runAction:_walkAction];
我正在检测球与蝙蝠的碰撞。通过以下代码
for (CCSprite *monster in _monsters) {
if (CGRectIntersectsRect(background.boundingBox, monster.boundingBox)) {
if (((background.position.x -5 > monster.position.x + (monster.contentSize.width/2)) && background.position.y > monster.position.y)) {
isCollision = 1;
[monstersToDelete addObject:monster];
}
// [monstersToDelete addObject:monster];
//[self addFishToBoat];
}
}
这里发生了碰撞是检测到碰撞,但它总是检测到与bat4的矩形碰撞..因为蝙蝠正在移动并且所有蝙蝠的cgrect都不同所以即使当bas离bat1非常远时它也会检测到碰撞,因为球的矩形将与bat4的矩形相交。
但是我希望只有当球会与不同的蝙蝠碰撞时才会发现碰撞,我的意思是当用蝙蝠,蝙蝠2,蝙蝠3,蝙蝠击打时,它只会检测到碰撞,而不是用蝙蝠4检测
答案 0 :(得分:0)
答案 1 :(得分:0)
您尝试使用此代码可能会对您有所帮助......
_contactListener = new MyContactListener();
_world->SetContactListener(_contactListener);
// Preload effect
[[SimpleAudioEngine sharedEngine] preloadEffect:@"hahaha.caf"];
std::vector<b2Body *>toDestroy;
std::vector<MyContact>::iterator pos;
for(pos = _contactListener->_contacts.begin();
pos != _contactListener->_contacts.end(); ++pos) {
MyContact contact = *pos;
b2Body *bodyA = contact.fixtureA->GetBody();
b2Body *bodyB = contact.fixtureB->GetBody();
if (bodyA->GetUserData() != NULL && bodyB->GetUserData() != NULL) {
CCSprite *spriteA = (CCSprite *) bodyA->GetUserData();
CCSprite *spriteB = (CCSprite *) bodyB->GetUserData();
if (spriteA.tag == 1 && spriteB.tag == 2) {
toDestroy.push_back(bodyA);
} else if (spriteA.tag == 2 && spriteB.tag == 1) {
toDestroy.push_back(bodyB);
}
}
}
std::vector<b2Body *>::iterator pos2;
for(pos2 = toDestroy.begin(); pos2 != toDestroy.end(); ++pos2) {
b2Body *body = *pos2;
if (body->GetUserData() != NULL) {
CCSprite *sprite = (CCSprite *) body->GetUserData();
[_spriteSheet removeChild:sprite cleanup:YES];
}
_world->DestroyBody(body);
}
if (toDestroy.size() > 0) {
[[SimpleAudioEngine sharedEngine] playEffect:@"hahaha.caf"];
}
有关此代码访问的详细信息
http://www.raywenderlich.com/606/how-to-use-box2d-for-just-collision-detection-with-cocos2d-iphone