Box2d bounding box for cocos2d child sprite.

Hey all, I'll explain my situation and post some relevant code which will lead to my question.

I am working on a space shooter iphone game, think Galaga to get a mental picture. I am using Cocos2d and Box2D (mostly just for collision detection). What I want is to have enemies that are a little more complex then just a single sprite that will be destroyed on contact. What I want is a sprite that has other sprites as destroyable parts. My plan was to have a parent sprite as the "body" of the enemy ship and add "ship components" as children.

The following is my init ship method:

Code:
-(id) initWithType:(ShipTypes)shipType
{
type = shipType;

NSString *frameName;

// location of component based on ship type, number of components
CGPoint locations[3][3] = { {ccp(-2,-13), ccp(36, -13), ccp(64, 0)},
                            {ccp(0,0), ccp(32, 0), ccp(64, 0)},
                            {ccp(0,0), ccp(32, 0), ccp(64, 0)}
                          };

switch (type)
{
    case ShipTypeStandard:
        frameName = @"bodyportion.png";
        numberOfComponents = [self randomComponentNumber];
        break;
    case ShipTypeOtherKind:
        frameName = @"otherKindShipBody.png";
    default:
        break;
}

//if ((self = [super initWithSpriteFrameName:frameName]))
if ((self = [super initWithFile:frameName]))
{
    for (int i = 1; i <= numberOfComponents; i++)
    {
        ShipComponent *shipComponent = [ShipComponent shipComponentInit];
        shipComponent.position = locations[type][i-1];
        [self addChild:shipComponent];

}

return self;
}


In my GameScene I create my ship and add it to the layer (I know using sprite sheets is the better way to do things but I am kind of just in proof of concept stage trying to get the enemies to work)

Code:
SpaceShip *ship = [SpaceShip shipWithType:(ShipTypes)0];
ship.position = [ship randomPosition];
[self addChild:ship];
[self addBoxBodyForAllSprites:ship];


The last bit of code is the addBoxBodyForAllSprites method:

Code:
-(void)addBoxBodyForAllSprites:(CCSprite *)sprite
{
CGPoint temp;
CGPoint originalPosition;

for (CCSprite *newSprite in [sprite children])
{
    originalPosition = newSprite.position;
    temp = [sprite convertToWorldSpace:newSprite.position];

    //newSprite.position = temp;

    b2BodyDef spriteBodyDef;
    spriteBodyDef.type = b2_dynamicBody;
    spriteBodyDef.position.Set(temp.x/PTM_RATIO, temp.y/PTM_RATIO);
    spriteBodyDef.userData = newSprite;

    b2Body *spriteBody = _world->CreateBody(&spriteBodyDef);

    b2PolygonShape spriteShape;

    spriteShape.SetAsBox(newSprite.contentSize.width/PTM_RATIO/2, newSprite.contentSize.height/PTM_RATIO/2);

    b2FixtureDef spriteShapeDef;
    spriteShapeDef.shape = &spriteShape;
    spriteShapeDef.density = 10.0;
    spriteShapeDef.isSensor = true;

    if (newSprite.tag == enemyComponentTag)
    {
        spriteShapeDef.filter.groupIndex = componentIndex;
    }

    spriteBody->CreateFixture(&spriteShapeDef);
}
}


Basically, the idea of the above method is to loop through the all the children sprites (ship components) of the parent sprite (the "body" of the ship).

The problem I am having is with the line spriteBodyDef.userData = newSprite;

If I have that line commented out, the bounding boxes will be in the correct position (around the sprite component) but I will not be able to get any of the information about the sprite when I later execute the line

Code:
ShipComponent *spriteA = (ShipComponent *) bodyA->GetUserData();


This makes sense since I never set it.

If I leave the line and have it get executed, the position of the bounding boxes is incorrect. It will be positioned at the position of the child sprite. For example, the position of the first component is at (-2,-13) and you can see the bounding box just barely visible in the bottom left hand corner (I have debug code enabled that will display the bounding box in pink).

I tried changing the position of the sprite to the world coordinates, setting the user data, and then changing the position of the sprite back to its original position but that did not work. I ended up with the same results. My understanding of userData is that it is just a pointer so I guess that makes sense.

So my question is how can I set the the position of a bounding box at the position of a sprite child and be able to set the user data? Is what I am looking for possible or do I / should I go about this problem a different way? I will appreciated any and all suggestions. If I was unclear or anyone needs more information let me know and I will try to clarify or elaborate.
So I have been searching various sites and forums all day and cannot really find anything of use. It is a little surprising to me as this seems like it would be a somewhat common thing to do. (The fact that I can't find anything makes me think that I am way off base in my approach. In that case I would love a little push in right direction).

Another example that seems like it would be common is what if there was a character holding a shield. If a projectile hits the shield, it is "blocked". If the projectile hits the character, the character takes damage.

Situations like this and from my original post are what I am looking for. If anyone has any input or links showing how this is done I would be real happy to see.

thanks.
Can you give a short description of what you're trying to do and why it doesn't work? No need to explain the technical details, just a general description. It may be easier to assist you that way.

As for the example in your second post, you can write a contact listener which tells you when collisions are detected and use it to determine whether the projectile should be blocked or damage the character.
Hi yyy,

I want to have a spaceship with destroyable parts. Each part will have it's own properties (hit points for example).

I want to have the destroyable parts as children of the "body" of the ship. (So when I move the "body" all the children move along with it).

The problem I am having is creating the Box2D bounding box in the position of children sprites. The position of the children sprite are relative to the position of the parent. If I try to position the bounding box using the position of the child sprite it uses that relative position. So in my example, my first ship component is (-2, -13) from the parent ("body" of the ship). When I create the bounding box it is at world coordinates (-2, -13). As in it is just barely visible at the very bottom left corner of my screen.

Code:
// Look at all the children (ship components) of the parent sprite ("body" of the ship)
for (CCSprite *newSprite in [sprite children])
{
    temp = [sprite convertToWorldSpace:newSprite.position];

    b2BodyDef spriteBodyDef;
    spriteBodyDef.type = b2_dynamicBody;
    spriteBodyDef.position.Set(temp.x/PTM_RATIO, temp.y/PTM_RATIO);
    spriteBodyDef.userData = newSprite;

...



If I do something like the above code it works until I execute the last line. The last line is important because later on when there is a collision I need that userData to get the properties (hit points for example) of the component.

Without the last line the bounding boxes are in the correct position but I don't have the user data. With the last line, the boxes are in the wrong position, but I have the user data.

Hope that helps. Thanks for reading.
So you're creating a new body for each destroyable part? If so then I don't think it's the right way to do that. I don't have much experience with that functionality yet but from what I understand you should instead add multiple fixtures to the ship's body. Start by creating one b2Body for the ship and then add the ship's body and destroyable parts as new fixtures to it, i.e.:

Code:
b2Body* ship = world->createBody(&bodyDef);
...
b2Fixture* shipBody = ship->createFixture(&shipBodyFixtureDef);
b2Fixture* part1 = ship->createFixture(&part1FixtureDef);
b2Fixture* part2 = ship->createFixture(&part2FixtureDef);


And so on.
Thanks for the reply yyy. While it looks like this is getting my on the right track I am still having some issues.

Here is what I am working with now:

Code:
-(void)addBoxBodyForAllSprites2:(CCSprite *)sprite
{
   //CGPoint temp;
   //temp = [sprite convertToWorldSpace:newSprite.position];
   
   b2BodyDef bodyDef;
   bodyDef.type = b2_dynamicBody;
   bodyDef.position.Set(sprite.position.x/PTM_RATIO, sprite.position.y/PTM_RATIO);
   bodyDef.userData = sprite;
   
   b2Body *body = _world->CreateBody(&bodyDef);
   
   for (CCSprite *newSprite in [sprite children])
   {
      b2PolygonShape shapeDef;
      shapeDef.SetAsBox(newSprite.contentSize.width/PTM_RATIO/2, newSprite.contentSize.height/PTM_RATIO/2);
      shapeDef.m_centroid.Set(newSprite.position.x / PTM_RATIO, newSprite.position.y / PTM_RATIO);
      
      b2FixtureDef fixtureDef;
      
      fixtureDef.shape = &shapeDef;
      
      fixtureDef.userData = newSprite;
      body->CreateFixture(&fixtureDef);
   }
}


So basically for addBoxBodyForAllSprites2:(CCSprite *)sprite, sprite is the parent "body" that has the children components. I create a body and then for each child component I create and add a fixture. This isn't working out for me. When I run my program, the pink debug box is where the body of the sprite would be, not where the components would be.

I feel like you got me on the right path but I am just missing something still. Any more advice? Anyone else have any input on this.

I guess my question has evolved to what is the proper way to add multiple fixtures to a body and how do you go about positioning those fixtures?

thanks for all the help thus far.
Seems to me like you're doing it right except I don't think you need to set the m_centroid in order to position the fixture - just use shapeDef.SetAsBox(float32 hx, float32 hy, const b2Vec2& center, float32 angle). The "center" argument will take care of the position of the fixture.
Excellent. The SetAsBox method in your last reply was exactly what I was looking for. Thanks.

I have another question now. When my "Bullet" object collides with one of the destroyable parts, I always get the properties of the last fixture that was created. Here is some of my collision code to hopefully help illustrate what is going on:

Code:
b2Body *bodyA = contact.fixtureA->GetBody();
b2Fixture *fixtureA = bodyA->GetFixtureList();
b2Filter filterA = fixtureA->GetFilterData();
      
b2Body *bodyB = contact.fixtureB->GetBody();
b2Fixture *fixtureB = bodyB->GetFixtureList();
b2Filter filterB = fixtureB->GetFilterData();
...

if (filterA.groupIndex == componentIndex)  && (filterB.groupIndex == bulletIndex)
{
    ShipComponent *spriteA = (ShipComponent *) fixtureA->GetUserData();
    //ShipComponent *spriteC = (ShipComponent *) fixtureA->GetNext()->GetUserData();

    Bullet *spriteB = (Bullet *) bodyB->GetUserData();
    ...
}


If I have a ship with 2 components and hit the left most component, I get some properties. If I hit the right most component, I get the same properties as the left most component.

So my question is how do I determine which actual fixture is being hit. It seems like that when I do GetFixtureList(), I just get the fixture at the Head of the List. I tried messing with GetNext() to see what else was in the list and got the expected results. I just can't figure out what I need to look at to see if this fixture is hit or if I need to go to the next entry in the fixture list.

Hopefully that makes some sense. Thanks for the help.
I don't think you need to look for the fixtures list when you already get fixtureA and fixtureB from the "contact" object. Try replacing this line:

Code:
b2Fixture *fixtureA = bodyA->GetFixtureList();


with:

Code:
b2Fixture *fixtureA = contact.fixtureA;


And obviously the same with fixtureB.
Thank you yyy. That is exactly what I was looking for. It is now working like I want / expected.

Thank you for all your help. I really appreciate it.

Original thread: https://box2d.org/forum/viewtopic.php?t=6815