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 rem开发者_如何学JAVAoved.
How can I achieve this?
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);
}
It's quite simple: world->DestroyBody(body)
.
And, small advice. For the good practice and performance you should not create bullets over and over again. Reuse it! Just make them invisible and reposition them at a position of a source.
精彩评论