Content Index
- What Is Forge2D?
- Main Class
- The World (world)
- Camera (CameraComponent)
- Camera and World: The Zoom Relationship
- Bodies (BodyComponent)
- Characteristics of Bodies and Physics Components
- Shapes
- Fixtures (Physical Properties)
- Forces, Impulses, and Velocity
- ContactCallbacks: Collisions and Contact Between Bodies
In this post, we will explore the core building blocks of Forge2D: a 2D physics engine based on the popular Box2D library, the same engine used to build games like Angry Birds. Understanding how Forge2D works with Flame will give you a solid foundation for creating realistic physics-based game experiences in Flutter.
If you do not have experience with Flame yet, I recommend starting here: learn how to build 2D games with Flutter and Flame before continuing with this chapter.
This chapter is meant as a reference: its goal is to introduce you to the basic features of Forge2D integrated with Flame so you can consult it anytime while working through the hands-on projects in the upcoming chapters.
What Is Forge2D?
Forge2D is a Dart port (and by extension, for Flutter and Flame) of the well-known Box2D physics engine. Box2D is an open-source library implementing a two-dimensional physics engine widely used in the game industry. Thanks to Forge2D, we can bring all that physics simulation power directly into our Flutter apps and games.
Important note on scaling: In
Forge2D, distances are calculated in physical meters, not pixels. If you use a very small zoom (such as1.0), objects can look tiny or move erratically due to precision limits in the engine. Keeping a base zoom of10.0is the standard recommended by the community: that way, 1 meter in the physics world equals 10 pixels, which simplifies calculations and avoids tunneling (objects passing through walls because they move too fast between frames).
As mentioned, you can use Forge2D standalone, either in pure Dart or directly in Flutter, with the following package:
$ dart pub add forge2d
$ flutter pub add forge2dOr, if you want to use it integrated with Flame (which is what we will do in this book), the right package is:
$ flutter pub add flame_forge2dFrom here on, every project in the book will use flame_forge2d as its main dependency to combine the physics engine with Flame's capabilities.
Main Class
In pure Flame, the base class for a game is FlameGame (or the generic Game). When integrating Forge2D, this base class is replaced by Forge2DGame, which internally extends FlameGame while adding the physics world and all its properties:
class MyGame extends Forge2DGame { }By extending Forge2DGame, we get direct access to the 2D physics engine and can interact with all its bodies, forces, and collisions.
For example, one of the first parameters typically configured in the main class is world gravity:
MyGame() : super(gravity: Vector2(0, 15));This Vector2 defines the direction and strength of gravity. With y = 15, dynamic bodies are pulled downward (just like in the real world), while x = 0 means there is no horizontal gravity. You can adjust these values to simulate, for example, lunar gravity or even reversed gravity.
In Forge2D, our components are called bodies. Unlike standard Flame components, they have real physical traits (mass, friction, bounce) and are the core objects of the Forge2D world.
The World (world)
Every game in Forge2D needs a "world" (world) where physical bodies exist and are simulated. The world is the main container for all physical entities: it manages gravity, processes collisions, and updates body positions every frame.
To create a body inside the world, we use:
return world.createBody(<BODY>)However, there is an important detail: Forge2D's World is not compatible with the World provided by standard Flame's FlameGame class. To access the Forge2D world properly from the Flame integration, we should import it with an alias to avoid naming conflicts:
import 'package:flame/camera.dart' as camera;
***
final cameraWorld = camera.World();And then add it directly from the Forge2DGame class:
add(cameraWorld);It is a somewhat unusual way to access the world, yet necessary given the current architecture of the integration. This API may be simplified in future versions of the package.
Camera (CameraComponent)
Just like in Flame, we need a camera to "see the world": it is the component that determines which slice of the physical world is visible on screen at any moment.
The basic camera setup in Forge2DGame looks like this:
cameraComponent = CameraComponent(world: cameraWorld);
cameraComponent.viewfinder.anchor = Anchor.topLeft;
add(cameraComponent);With Anchor.topLeft, we tell it that the camera's coordinate origin starts at the top-left corner of the screen, which is usually the most intuitive behavior for 2D games.
Camera and World: The Zoom Relationship
There is a close relationship between the camera and the world: the camera defines which part of the world is viewed and at what scale. This is especially relevant in Forge2D because the Forge2DGame class sets a default zoom of 10.0.
This means components will appear visually much larger than in a normal Flame game. The reason for this default value is to prevent bodies from hitting the physics engine's speed limit too quickly (an issue that arises if you use zoom = 1.0 with Forge2D's meter units).
The practical effect of this zoom is that world coordinates do not map 1:1 to pixels. If you place an element at:
10 x 10 (world coordinates)
What actually happens on screen is that it renders at:
100 x 100 pixels
Precisely because of the 10.0 zoom factor.
To work properly with these coordinates, you can use the screenToWorld() method, which converts screen coordinates (in pixels) to physical world coordinates. For example:
cameraComponent.viewport.size
>> Vector2 ([929,918])When converting with screenToWorld():
screenToWorld(cameraComponent.viewport.size)
>> Vector2 ([92.9,91.8])If instead you prefer working directly in pixels, you can change the zoom when initializing the game:
class MyGame extends Forge2DGame {
MyGame() : super(zoom: 1);
}With zoom = 1, world coordinates match screen pixels directly:
screenToWorld(cameraComponent.viewport.size)
>> Vector2 ([929,918])In short, screenToWorld() returns coordinates adjusted for the active zoom level. Reducing zoom from 10 to 1 makes objects take up visually 1/10 of their previous size, which can be helpful for scenes with many small elements.
Bodies (BodyComponent)
Bodies are instances of classes that extend BodyComponent. They are the fundamental objects of the physical world in Forge2D: unlike standard Flame components, BodyComponent instances actively take part in the physics simulation (gravity, collisions, forces). There are three body types:
- Static (
BodyType.static): A body with zero mass and zero velocity. It does not move from forces, though it can be repositioned manually. Ideal for floors and walls. - Dynamic (
BodyType.dynamic): A body with positive mass and velocity determined by applied forces. It is the most common type for characters and interactive objects. - Kinematic (
BodyType.kinematic): A body with zero mass but velocity set by the programmer. It does not react to external forces, yet it collides with dynamic bodies. Great for moving platforms.
| Body Type | Mass | Velocity | Typical Use |
|---|---|---|---|
| Static | 0 | 0 | Floors, walls, fixed obstacles. |
| Dynamic | Positive | Determined by forces | Player, enemies, throwable objects. |
| Kinematic | 0 | Set by the user | Moving platforms, elevators. |
To create a body, we define a class that extends BodyComponent and override the createBody() method:
class MyBody extends BodyComponent {
@override
Body createBody() {
}
}Inside createBody(), we instantiate a BodyDef with the body's configuration: initial position, type, angle, and so on:
final bodyDef = BodyDef(
position: Vector2(worldSize.x / 2, 0),
type: BodyType.dynamic,
);This example creates a dynamic body centered horizontally and placed at the top of the screen.
The createBody() method is called automatically by the BodyComponent lifecycle. Once run, the body is stored in the internal body property, through which we can access it anytime to apply forces, change its velocity, or read its position:
// Access the body from any method in the component
body.applyForce(Vector2(10, 0));You can also customize the component's appearance by assigning a color through the paint property:
paint = BasicPalette.red.paint();Characteristics of Bodies and Physics Components
In this section, we will see how to customize bodies in Forge2D and how to apply forces to interact with the physics engine. It is more of a reference section than a step-by-step tutorial, but it will help you understand the engine's architecture before seeing real examples in the next chapters.
Shapes
Every body in Forge2D needs a shape (Shape) that defines its collision geometry. You can think of Shape objects like Flame's hitboxes, with the added trait that they also take part in the physics simulation. Available shapes include circles, rectangles, and arbitrary polygons.
To create a circular shape:
final shape = CircleShape()..radius = .35;To create a rectangular box:
final shape = PolygonShape()..setAsBoxXY(.15, 1.25);You can check all available shapes in the official flame_forge2d documentation.
Fixtures (Physical Properties)
Fixtures are what give a body's shape real physical properties. Thinking of the real world, a rubber ball and a bowling ball can share the same spherical shape, yet behave very differently: one bounces a lot, the other barely bounces at all, and their weights are completely different. Those differences are modeled with FixtureDef in Forge2D.
A FixtureDef has three main properties:
- Density (
density): Mass per unit area (kg/m²). Together with size, it determines the body's weight. - Friction (
friction) [0, 1]: Resistance force to sliding between surfaces. A value of0means no friction (like ice), and1is maximum friction. - Restitution (
restitution) [0, 1]: Elasticity of the body during collisions. A value of0means no bounce (inelastic impact) and1is a perfect bounce.
To create and attach a FixtureDef to a body:
final fixtureDef = FixtureDef(shape);
world.createBody(bodyDef)..createFixture(fixtureDef);Keep in mind that fixtures are defined on the Shape, not directly on the body. All of this logic should live inside the createBody() method; once the component lifecycle runs it automatically, you can access the configured body via the body property.
Forces, Impulses, and Velocity
Once you have a body set up, you can move it by applying different kinds of physical quantities. All of these methods are called on the body property:
- Force (
applyForce): Applies a continuous force at a point on the body. Velocity changes gradually over time. Ideal for simulating progressive acceleration, such as a vehicle accelerating from rest. - Linear impulse (
applyLinearImpulse): Applies an instantaneous force that changes the body's velocity immediately. Equivalent to a hit or sudden collision. The actual effect depends on the receiving body's mass. - Linear velocity (
linearVelocity): Directly assigns a velocity to the body, regardless of mass or gravity. Useful when you want full control over movement, such as on a kinematic body.
All of these methods take a Vector2 indicating the direction and magnitude of movement. For example:
— To move the body only along the horizontal axis: Vector2(50, 0)
— To apply an upward jump: Vector2(0, -20) (negative because Y grows downward)
The key difference: applyForce and applyLinearImpulse respect mass, body type, and gravity, whereas assigning linearVelocity directly ignores all of those factors and applies the velocity as given.
You can learn more about body methods and properties in the official forge2d documentation.
ContactCallbacks: Collisions and Contact Between Bodies
Just as Flame provides its own collision detection system between components, Forge2D has its physical equivalent: the ContactCallbacks mixin. By mixing it into a BodyComponent, you can detect when two bodies start or stop touching through two methods:
beginContact(Object other, Contact contact): Called when two bodies begin touching.endContact(Object other, Contact contact): Called when two bodies stop touching.
The parameters for both methods are:
Object other: TheBodyComponentinvolved in the contact.Contact contact: An object with detailed information about the contact (impact point, normal, and so on).
Just like with collisions in Flame, you can use these callbacks to play sounds, show visual effects, update scores, or run any other game logic.
For the contact system to work properly, it is essential to set userData: this in the BodyDef of the bodies you want to monitor. Without this, Forge2D cannot identify which BodyComponent corresponds to each physical body:
BodyDef bodyDef = BodyDef(
***
userData: this);The userData property acts as a bridge between the engine's physical body and the Flame component that represents it, allowing Forge2D to resolve contacts and route them to the right BodyComponent.
Next step: learn how to build apps and games adaptive to screen size.