Page 1 of 1

Adding objects during execution (randomly)

Posted: Mon Nov 22, 2010 3:00 pm
by xissburg
I'm working with chipmunk+cocos2d in an iPad application.

I want to add objects to the world while the physics simulation is running.

One approach would be to add a kind of 'pre step callback' to be run in every iteration of the main loop of the physics simulation, but afaik there's no such functionality in chipmunk, or am I wrong? Another similar one would be to add a post step callback, which exists but I can't add a post step callback that will be executed forever, they're ran just once and removed.

Other approach is to use another thread which randomly adds these objects, which is what is partially working now. In this thread I add one post step callback and then sleep for a few random seconds. In this callback I just add one more object to the world. But at one time I get a EXC_BAD_ACCESS, and my app crashes, and its is probably a concurrency problem.

Then, what is the right way to do this?


Thanks in advance.

Re: Adding objects during execution (randomly)

Posted: Mon Nov 22, 2010 3:14 pm
by slembcke
I'm not quite sure why you would want a pre-step callback. You can just add objects to the space before calling cpSpaceStep(). You don't really need any special functionality to do it. The problem comes when Chipmunk is iterating one of its data structures and you add or remove things from it.

If you want to use threads, you need to put lock on your accesses to the space, but honestly you don't want to use threads.

Re: Adding objects during execution (randomly)

Posted: Mon Nov 22, 2010 3:41 pm
by xissburg
Hm I see...since I'm using SpaceManager I don't manage the physics main loop, I don't call cpSpaceStep() myself, thats why I was talking about a pre step call, which is what I'd like to do. Using threads may be a good approach, I think there won't be many attempts to access the critical section at the same time by the two threads because I won't add objects frequently, but I don't want this additional overhead, its unnecessary.

Do you know whether this is easy to do in SpaceManager?

Thanks.

Re: Adding objects during execution (randomly)

Posted: Mon Nov 22, 2010 5:27 pm
by slembcke
Just schedule a Cocos2D timer to add the objects then. Like I said, the only time you need to worry about adding or removing objects is when you are in a callback from Chipmunk. Any other time is 100% safe because Cocos2D is not multithreaded and you will never get a timer callback that happens while cpSpaceStep() is running.

Re: Adding objects during execution (randomly)

Posted: Tue Nov 23, 2010 12:07 am
by mobilebros
slembcke is right, you should have no problems. I do the exact thing you're describing all the time (with SpaceManager).

Re: Adding objects during execution (randomly)

Posted: Tue Nov 23, 2010 12:10 pm
by xissburg
Wow that is neat, works perfectly ! Thank you guys.