Handle removal of sprite physics bodies during the physics simulation
diff --git a/examples/game/test_physics.dart b/examples/game/test_physics.dart index a7c23f9..2a9ad88 100644 --- a/examples/game/test_physics.dart +++ b/examples/game/test_physics.dart
@@ -83,6 +83,7 @@ void myCallback(PhysicsContactType type, PhysicsContact contact) { print("CONTACT type: $type"); + contact.nodeB.removeFromParent(); } bool handleEvent(SpriteBoxEvent event) {
diff --git a/packages/flutter_sprites/lib/physics_body.dart b/packages/flutter_sprites/lib/physics_body.dart index 99c8ea4..e9446b6 100644 --- a/packages/flutter_sprites/lib/physics_body.dart +++ b/packages/flutter_sprites/lib/physics_body.dart
@@ -120,7 +120,7 @@ void _detach() { if (_attached) { - _physicsNode.b2World.destroyBody(_body); + _physicsNode._bodiesScheduledForDestruction.add(_body); _attached = false; } }
diff --git a/packages/flutter_sprites/lib/physics_node.dart b/packages/flutter_sprites/lib/physics_node.dart index bc19c6a..12ea4f8 100644 --- a/packages/flutter_sprites/lib/physics_node.dart +++ b/packages/flutter_sprites/lib/physics_node.dart
@@ -31,6 +31,8 @@ _ContactHandler _contactHandler; + List<box2d.Body> _bodiesScheduledForDestruction = []; + double b2WorldToNodeConversionFactor = 500.0; Offset get gravity { @@ -57,6 +59,9 @@ } void _stepPhysics(double dt) { + // Remove bodies that were marked for destruction during the update phase + _removeBodiesScheduledForDestruction(); + // Calculate a step in the simulation b2World.stepDt(dt, 10, 10); @@ -71,6 +76,16 @@ body._node._setRotationFromPhysics(degrees(b2Body.getAngle())); } + + // Remove bodies that were marked for destruction during the simulation + _removeBodiesScheduledForDestruction(); + } + + void _removeBodiesScheduledForDestruction() { + for (box2d.Body b2Body in _bodiesScheduledForDestruction) { + b2World.destroyBody(b2Body); + } + _bodiesScheduledForDestruction.clear(); } void _updatePosition(PhysicsBody body, Point position) { @@ -257,6 +272,11 @@ b2Contact.isTouching(), b2Contact.isEnabled() ); + + if (type == PhysicsContactType.postSolve) { + + } + // Make callback info.callback(type, contact);