Destroying a body causes a crash?

Jul 29, 2012 at 12:48 PM


I've got a class named "Bullet", and, as the name implies, it's a bullet that is spawned when the user presses the fire button. Now, the bullets are destroyed if the bullet travels far enough from the player or if the lifetime of the bullet exceeds a certain amount of seconds.

I use body.Dispose() to get rid of the bullet bodies, but it causes random crashes every now and then. Sometimes I can shoot bullets for a few minutes, sometimes it crashes right on the first bullet.

The call stack tells me that the crash happens in DynamicTree.cs, in the Query() method. It's also weird that it's not always the same line of code - it varies every time. So far I've got call stacks to these rows:

int nodeId = _stack.Pop();

The exception I get is IndexOutOfRangeException.

What could possibly be the problem? The world and the body.Dispose() call are ran in the same thread, so it shouldn't be a threading problem as was the case with another problem in the earlier discussions.

Jul 29, 2012 at 1:32 PM

Does this also happen if you just call World.RemoveBody() instead of Body.Dispose()? Could it be that the DynamicTree holds some stuff from the body that are not released when the GC tries to kick in or vice-versa.

Jul 29, 2012 at 2:07 PM

Yeah, I've tried both ways, there's no difference. I surrounded the insides of the Query() function into try-catch, and after a while of random single messages, the function goes batshit crazy, causing exceptions every frame, even if there's no bodies disposed.

Aug 7, 2012 at 3:30 AM

Are you doing this inside a collision event? I implemented a non-locking simulation in Farseer that should enable you to remove objects while an update is calculated, however, sometimes it can go crazy. If you are doing this in the OnCollision event, I would recommend that you return false inside it to avoid the engine calculating any further forces on the bullets as they are destroyed.

Aug 7, 2012 at 6:46 AM

I fiddled around with the code, and I noticed that while I was rapidly generating bodies, it wasn't caused by the destruction, but the creation. It only happens with the DynamicTreeBroadPhase. If I use QuadTree, this problem won't happen. I don't use the OnCollision / OnSeparation events with the bullets, instead I have a timer in the update function that checks whether or not the bullet has "lived" long enough.

Aug 28, 2012 at 12:51 AM

Could you post the code that replicates this? I would prefer it if you implemented it inside the Testbed project and uploaded the .cs file to a service like or post it here if it is small.