Page 1 of 1
How to delete bodies which have gone off screen?
Posted: Fri Feb 12, 2010 9:08 pm
by mh@pixar.com
What's the right way to delete a body?
In Demos/Plink.c, I changed this code:
Code: Select all
// Iterate over all of the bodies and reset the ones that have fallen offscreen.
static void
eachBody(cpBody *body, void *unused)
{
if(body->p.y < -260 || fabsf(body->p.x) > 340){
cpFloat x = rand()/(cpFloat)RAND_MAX*640 - 320;
body->p = cpv(x, 260);
}
}
to:
Code: Select all
// Delete the bodies which have fallen off-screen
static void
eachBody(cpBody *body, void *unused)
{
if(body->p.y < -260 ){
cpBodyFree(body);
}
}
expecting that this would delete all the bodies as they fell off-screen, but it gives me a segmentation fault.
Is there something else I need to do to delete bodies?
Re: How to delete bodies which have gone off screen?
Posted: Sat Feb 13, 2010 11:28 am
by slembcke
You need to remove the body from the space before you free it.
Re: How to delete bodies which have gone off screen?
Posted: Sun Feb 14, 2010 3:49 am
by mh@pixar.com
Sweet, thanks!
For the record, here's how to change the Plink demo so that it's a one-shot dump of pentagons that get cleaned up once they fall off the screen.
1. Add this line to the "//Add lots of pentagons" loop. This is so we can free the shape attached to the body.
2. remove the shape and body from the space, then free the shape and body. It doesn't seem to matter if you remove/free the shape first or the body first, so long as you keep in mind that you lose the pointer to the shape when you free the body.
ddd
Code: Select all
if(body->p.y < -260 ){
cpSpaceRemoveShape(space, body->data);
cpSpaceRemoveBody(space, body);
cpShapeFree(body->data);
cpBodyFree(body);
}
Re: How to delete bodies which have gone off screen?
Posted: Sat Feb 20, 2010 1:07 pm
by Rb_
Any idea how this works with iphone development using an NSTimer?
Currently I have my main 'setupChipmunk' method creating the body & shapes, then at the bottom it starts the NSTimer which within its method allows me to check and see when its fallen off the bottom of the screen :
Code: Select all
- (void)tick:(NSTimer *)timer {
// Tell Chipmunk to take another "step" in the simulation
cpSpaceStep(space, 1.0f/60.0f);
if(ball.center.y > self.view.bounds.size.height) {
score_int++;
score.text = [NSString stringWithFormat:@"%d",score_int];
ballBody->data=shape
cpSpaceRemoveShape(space, ballBody->data);
cpSpaceRemoveBody(space, ballBody);
cpShapeFree(ballBody->data);
cpBodyFree(ballBody);
Using the above it currently fires back a ballBody undeclared method. I'm new to iphone development so its probably something ridiculously obvious, I understand that the reason it's undeclared is down to this method being another private segment of the application, but I am wholly unsure on how to make ballBody global so I can access it.
Any help would be massively appreciated.
Thanks in advance
