i am using cocos2d and having many sprites and bodies. each sprite has its body, and each kind of sprite has a tag. (see next) .
when 2 sprites are contact each other, i can discover that and i want them to disappear.
THE problem is that i have many sprites from the same kind(having the same tag) so when i clean a sprite, it does clean the last sprite that was created and not the one i want.
my function that create a sprites from the same kind is :
-(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];
}
which is tagged as 2.
when i see a contact with this :
//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");
}
now the sprite that disappear is not that one that touched here, but the one that was created after him ..
HOW can i erase a SPECIFIC sprite-the one that just touched another one ??
not the LAST one created ?
thanks a lot
If two sprites are Collide you remove any one like below: