When using Phaser, you can leverage helper functions to bridge the gap between Phaser's pixel-based coordinate system and Box2D's meter-based system.
Workflow:
- Set World Scale: Use
SetWorldScale(pixelsPerMeter) to define the conversion ratio. - Pixel-to-Meter Conversion: Use
pxmVec2(x, y) to convert pixel coordinates into b2Vec2 objects required by Box2D. - Rotation Helpers: Use
RotFromRad(radians) to create rotation objects easily. - Phaser Debug Draw: Use
new PhaserDebugDraw(graphicsObject, width, height, scale) to render the physics world onto a Phaser Graphics object.
Example Integration:
// In Phaser Scene create()
SetWorldScale(40);
const debug = this.add.graphics();
const world = CreateWorld({ worldDef: b2DefaultWorldDef() });
const worldId = world.worldId;
// Create a body using pixel coordinates
CreateBoxPolygon({
worldId,
type: DYNAMIC,
position: pxmVec2(630, 64),
size: 1,
density: 1.0,
friction: 0.2,
color: b2HexColor.b2_colorGold
});
this.worldDraw = new PhaserDebugDraw(debug, 1280, 720, GetWorldScale());
// In Phaser Scene update()
update (time, delta)
{
WorldStep({ worldId, deltaTime: delta });
this.debug.clear();
b2World_Draw(worldId, this.worldDraw);
}