physicsWorld property

World get physicsWorld

The underlying Forge2D physics world.

It is created the first time it is used rather than in the constructor, because Forge2D has to be initialized before a world can be created, and on the web that initialization is asynchronous. Forge2DGame awaits it in its onLoad; if you use a Forge2DWorld outside of a Forge2DGame you have to await initializeForge2D() yourself before the world is used.

The world is never destroyed by the component, so that it can be re-added to the component tree later. Since it holds native resources that are not garbage collected, and Box2D allows only a limited number of simultaneous worlds, call physicsWorld.destroy() when you are permanently done with it, for example when you tear down a game that you don't intend to show again.

Implementation

forge2d.World get physicsWorld {
  final existingWorld = _physicsWorld;
  if (existingWorld != null) {
    return existingWorld;
  }
  final createdWorld = forge2d.World(
    gravity: _gravity,
    definition: _definition,
  );
  if (!createdWorld.isValid) {
    // Checked at runtime rather than with an assert, since an invalid world
    // is cached and used by every later step and API call, which would crash
    // far from the cause in a release build where asserts are stripped.
    throw StateError(
      'The physics world could not be created. Box2D allows a limited number '
      'of simultaneous worlds, and Forge2D worlds are not freed '
      'automatically, so call physicsWorld.destroy() on the worlds that you '
      'are done with.',
    );
  }
  return _physicsWorld = createdWorld;
}