Search code examples
cocos2d-iphonebox2dbox2d-iphoneprojectile

How to destroy a b2Body in Box2D (cocos2d)? After checking the traveld distance


I have bullets in box2d/cocos2d-for-iphone. They are flying fine...but I want to destroy these bullets after they traveld a certain distance. for example after a bullet "flew" 480px it should be removed.

How can I achieve this?


Solution

  • To count the distance, when creating a bullet store it's position somewhere. Then every step check:

    b2Vec2 diff = bullet->GetPosition() - startPosition;
    if (diff.Length() > MaxLen)
    {
        world->DestroyBody(bullet);
    }
    

    EDIT:

    if you want to calculate the path length then store somewhere the previous position and the path length, that is initially 0:

    b2Vec2 diff = bullet->GetPosition() - prevPosition;
    pathLength += diff.Length();
    if (pathLength > MaxLen())
    {
        //destroy bullet//world->DestroyBody(bullet);
    }