0

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?

mad_manny
  • 1,081
  • 16
  • 28
cocos2dbeginner
  • 2,185
  • 1
  • 31
  • 58

2 Answers2

1

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.

gixdev
  • 570
  • 3
  • 6
1

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);
}
Andrew
  • 24,218
  • 13
  • 61
  • 90
  • that's not excatly what I want..my bullet could travel 400 px. But in a circular motion...than this code wouldn't be valid. Every time the bullet moves...i need to add every pixel(s) (x,y) moved to a float....but I'm not so familiar with maths..any help? – cocos2dbeginner Jul 09 '11 at 13:19
  • If the position of the bullet has changed(either by x or/and y) from previous position than +1 pixel has traveled. – gixdev Jul 09 '11 at 13:42