我正在使用cocos2d并拥有许多精灵和身体。每个精灵都有自己的身体,每种精灵都有一个标签。 (见下)。
当2个精灵相互接触时,我可以发现它并且我希望它们消失。
问题是我有很多来自同一类型的精灵(具有相同的标签)所以当我清理一个精灵时,它会清理最后创建的精灵,而不是我想要的精灵。
我创建同一种精灵的函数是:
-(void)fruit1:(int) randomForCoordinates
{
//define sprite
fruit1=[CCSprite spriteWithFile:@"fruit1.png"];
fruit1.tag=2;
fruit1.position=ccp(randomForCoordinates,500);
//add fruit
b2BodyDef spriteBodyDef;
spriteBodyDef.type =b2_dynamicBody;
spriteBodyDef.position.Set(fruit1.position.x/PTM_RATIO,fruit1.position.y/PTM_RATIO);
spriteBodyDef.userData = fruit1;
fruit1body = world->CreateBody(&spriteBodyDef);
b2PolygonShape spriteShape; //b2polygon-for box shape
spriteShape.SetAsBox(fruit1.contentSize.width/PTM_RATIO/2,fruit1.contentSize.height/PTM_RATIO/2); //for b2polygon
b2FixtureDef spriteShapeDef;
spriteShapeDef.shape = &spriteShape;
spriteShapeDef.density = 10.0;
spriteShapeDef.isSensor = false;
fruit1body->CreateFixture(&spriteShapeDef);
[self addChild:fruit1];
}
标记为2。 当我看到与此联系时:
//cotact listener
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();
//check if collision between to bodies
if( bodyA->GetUserData() !=NULL && bodyB->GetUserData() !=NULL) //if ((contact.fixtureA == _bottomFixture && contact.fixtureB == _ballFixture) ||(contact.fixtureA == _ballFixture && contact.fixtureB == _bottomFixture))
{
CCSprite *actor = (CCSprite*)bodyA->GetUserData();
CCSprite *actorb = (CCSprite*)bodyB->GetUserData();
//touch
if ([actorb tag] == 2 && [actor tag]== 1)
{
[fruit1.parent removeChild:fruit1 cleanup:YES];
NSLog(@"touch1");
}
现在消失的精灵不是那里触及的精灵,而是那个在他身后创造的精灵......
我如何擦除一个SPECIFIC精灵 - 刚刚触及另一个精灵? 不是最后一个创建的?
非常感谢
答案 0 :(得分:1)
如果有两个精灵碰撞,你可以删除下面的任何一个精灵:
if( bodyA->GetUserData() !=NULL && bodyB->GetUserData() !=NULL) //if ((contact.fixtureA == _bottomFixture && contact.fixtureB == _ballFixture) ||(contact.fixtureA == _ballFixture && contact.fixtureB == _bottomFixture))
{
CCSprite *actor = (CCSprite*)bodyA->GetUserData();
CCSprite *actorb = (CCSprite*)bodyB->GetUserData();
//touch
if ([actorb tag] == 2 && [actor tag]== 1)
{
[self removeChild:actor cleanup:YES];
//(or)
[self removeChild:actorb cleanup:YES];
NSLog(@"touch1");
}