### HTML Structure Source: https://github.com/phaserjs/phaser-box2d/blob/main/getting-started/GETTING-STARTED.md The basic HTML structure for the Phaser Box2D example. ```html Phaser Box2D Example
``` -------------------------------- ### Creating a Box2D World Source: https://github.com/phaserjs/phaser-box2d/blob/main/getting-started/GETTING-STARTED.md Code to create a Box2D world with custom gravity. ```js import { CreateWorld, b2DefaultWorldDef, b2Vec2 } from '../lib/PhaserBox2D.js'; // create a definition for a world using the default values let worldDef = b2DefaultWorldDef(); // change some of the default values worldDef.gravity = new b2Vec2(0, -10); // create a world object and save the ID which will access it let world = CreateWorld({ worldDef: worldDef }); ``` -------------------------------- ### Create Debug Draw Source: https://github.com/phaserjs/phaser-box2d/blob/main/getting-started/GETTING-STARTED.md Creates a debug draw renderer for the Box2D world. ```javascript m_draw = CreateDebugDraw(canvas, ctx, m_drawScale); ``` -------------------------------- ### Complete Example: main.js Source: https://github.com/phaserjs/phaser-box2d/blob/main/README.md A comprehensive example demonstrating the setup of physics world, objects, and debug drawing within a single JavaScript file. ```javascript // Import Library Functions import { CreateBoxPolygon, CreateCircle, CreateWorld, WorldStep } from '../lib/PhaserBox2D.js'; import { CreateDebugDraw, RAF } from '../lib/PhaserBox2D.js'; import { b2BodyType, b2DefaultBodyDef, b2DefaultWorldDef, b2HexColor } from '../lib/PhaserBox2D.js'; import { b2Rot, b2Vec2 } from '../lib/PhaserBox2D.js'; import { b2World_Draw } from '../lib/PhaserBox2D.js'; // ** Debug Drawing ** // set the scale at which you want the world to be drawn const m_drawScale = 30.0; // get the canvas element from the web page const canvas = document.getElementById('myCanvas'); const ctx = canvas.getContext('2d'); // create the debug drawing system const m_draw = CreateDebugDraw(canvas, ctx, m_drawScale); // ** Physics World Creation ** // create a definition for a world using the default values let worldDef = b2DefaultWorldDef(); // change some of the default values worldDef.gravity = new b2Vec2(0, -10); // create a world object and save the ID which will access it let world = CreateWorld({ worldDef:worldDef }); // ** Physics Object Creation ** // a box that will fall const box = CreateBoxPolygon({ worldId:world.worldId, type:b2BodyType.b2_dynamicBody, position:new b2Vec2(0, 8), size:2, density:1.0, friction:0.2, color:b2HexColor.b2_colorGold }); // a ball that will fall and land on the corner of the box const ball = CreateCircle({ worldId:world.worldId, type:b2BodyType.b2_dynamicBody, position:new b2Vec2(1.5, 12), radius:1, density:1.0, friction:0.5, color:b2HexColor.b2_colorRed }); // a static ground which is sloped up to the right const groundBodyDef = b2DefaultBodyDef(); groundBodyDef.rotation = new b2Rot(Math.cos(Math.PI * .03), Math.sin(Math.PI * .03)); const ground = CreateBoxPolygon({ worldId:world.worldId, type:b2BodyType.b2_staticBody, bodyDef: groundBodyDef, position:new b2Vec2(0, -6), size:new b2Vec2(20, 1), density:1.0, friction:0.5, color:b2HexColor.b2_colorLawnGreen }); // ** Define the RAF Update Function ** function update(deltaTime, currentTime, currentFps) { // ** Step the Physics ** WorldStep({ worldId: world.worldId, deltaTime: deltaTime }); // ** Debug Drawing ** ctx.clearRect(0, 0, canvas.width, canvas.height); b2World_Draw(world.worldId, m_draw); } // ** Trigger the RAF Update Calls ** RAF(update); ``` -------------------------------- ### Phaser Scene and Game Configuration Source: https://github.com/phaserjs/phaser-box2d/blob/main/getting-started/GETTING-STARTED.md Sets up a basic Phaser Scene and game configuration, including importing Phaser and defining the game canvas and scene. ```javascript import * as Phaser from '../lib/phaser.esm.js'; class Example extends Phaser.Scene { constructor () { super(); } create () { } update (time, delta) { } } const config = { type: Phaser.AUTO, width: 1280, height: 720, scene: Example }; const game = new Phaser.Game(config); ``` -------------------------------- ### ConvertScreenToWorld Example Source: https://github.com/phaserjs/phaser-box2d/blob/main/docs/index.html Example of converting screen coordinates to world coordinates. ```javascript // Convert mouse click position to world coordinates const worldPos = ConvertScreenToWorld(myCanvas, 30, mousePos); ``` -------------------------------- ### Update Loop for Physics Step and Rendering Source: https://github.com/phaserjs/phaser-box2d/blob/main/getting-started/GETTING-STARTED.md The update method steps the Box2D world, clears the debug graphics, and re-renders the world bodies. ```javascript update (time, delta) { const worldId = this.world.worldId; WorldStep({ worldId, deltaTime: delta }); this.debug.clear(); b2World_Draw(worldId, this.worldDraw); } ``` -------------------------------- ### Creating Dynamic Bodies Source: https://github.com/phaserjs/phaser-box2d/blob/main/getting-started/GETTING-STARTED.md Code to create a dynamic box and a dynamic circle to drop onto the ground. ```js const box = CreateBoxPolygon({ worldId: world.worldId, type: b2BodyType.b2_dynamicBody, position: new b2Vec2(0, 8), size: 2, density: 1.0, friction: 0.2, color: b2HexColor.b2_colorGold }); const ball = CreateCircle({ worldId: world.worldId, type: b2BodyType.b2_dynamicBody, position: new b2Vec2(1.7, 12), radius: 1, density: 1.0, friction: 0.5, color:b2HexColor.b2_colorRed }); ``` -------------------------------- ### RevoluteJointConfig Example Source: https://github.com/phaserjs/phaser-box2d/blob/main/README.md Example configuration for a revolute joint. ```javascript /** * @typedef {Object} RevoluteJointConfig * @property {b2WorldId} worldId - ID for the world in which the bodies and joint exist. * @property {b2RevoluteJointDef} [jointDef] - A pre-existing b2RevoluteJointDef. * @property {b2BodyId} bodyIdA - The first body to connect with this joint. * @property {b2BodyId} bodyIdB - The second body to connect with this joint. */ ``` -------------------------------- ### World Initialization and Ground Creation Source: https://github.com/phaserjs/phaser-box2d/blob/main/getting-started/GETTING-STARTED.md Initializes the Box2D world scale and creates a ground body using Phaser's Graphics Game Object and Box2D helper functions. ```javascript SetWorldScale(40); const debug = this.add.graphics(); const world = CreateWorld({ worldDef: b2DefaultWorldWorldDef() }); const worldId = world.worldId; ``` ```javascript const groundBodyDef = b2DefaultBodyDef(); groundBodyDef.rotation = RotFromRad(-0.06); CreateBoxPolygon({ worldId, type: STATIC, bodyDef: groundBodyDef, position: pxmVec2(640, -600), size: new b2Vec2(20, 1), density: 1.0, friction: 0.5, color: b2HexColor.b2_colorLawnGreen }); ``` -------------------------------- ### RAF Example Source: https://github.com/phaserjs/phaser-box2d/blob/main/docs/index.html Example of how to use the RAF function to create an animation loop. ```javascript const callback = (deltaTime, totalTime, currentFps) => { // Your update logic here }; RAF(callback); ``` -------------------------------- ### CreateMouseJoint Example Source: https://github.com/phaserjs/phaser-box2d/blob/main/README.md Configuration and creation of a mouse joint between two bodies. ```javascript /** * @typedef {Object} MouseJointConfig * @property {b2WorldId} worldId - ID for the world in which the bodies and joint exist. * @property {b2MouseJointDef} [jointDef] - A pre-existing b2MouseJointDef. * @property {b2BodyId} bodyIdA - The first (usually static) body to connect with this joint. * @property {b2BodyId} bodyIdB - The second (usually dynamic) body to connect with this joint. * @property {b2Vec2} [target] - The initial world target point. * @property {number} [hertz] - The response frequency. * @property {number} [dampingRatio] - The damping ratio. * @property {number} [maxForce] - The maximum force that can be exerted to reach the target point. * @property {boolean} [collideConnected] - Whether the connected bodies should collide. * e.g. worldId:worldId, bodyIdA:mouseCircle.bodyId, bodyIdB:mouseBox.bodyId, target:new b2Vec2(0, 0), hertz:30.0, dampingRatio:0.999, maxForce:35000 */ /** * Creates a mouse joint between two bodies. * @param {MouseJointConfig} data - Configuration for the mouse joint. * @returns {{jointId: b2JointId}} The ID of the created mouse joint. */ export function CreateMouseJoint(data) ``` -------------------------------- ### AttachImage Example Source: https://github.com/phaserjs/phaser-box2d/blob/main/docs/index.html Example of attaching an image to a Box2D body. ```javascript const worldId = 1; const bodyId = 1; const imagePath = "assets/images/"; const imageName = "myImage.png"; const offset = new b2Vec2(0, 0); const scale = new b2Vec2(1, 1); const sourcePos = new b2Vec2(0, 0); const sourceSize = new b2Vec2(32, 32); const shapeWithImage = AttachImage(worldId, bodyId, imagePath, imageName, offset, scale, sourcePos, sourceSize); ``` -------------------------------- ### CreateWheelJoint Example Source: https://github.com/phaserjs/phaser-box2d/blob/main/README.md Configuration and creation of a wheel joint between two bodies. ```javascript /** * @typedef {Object} * @property {b2WorldId} worldId - ID for the world in which the bodies and joint exist. * @property {b2WheelJointDef} [jointDef] - A pre-existing b2WheelJointDef. * @property {b2BodyId} bodyIdA - The first body to connect with this joint. * @property {b2BodyId} bodyIdB - The second body to connect with this joint. * @property {b2Vec2} [anchorA] - Local position of the anchor point on the first body. * @property {b2Vec2} [anchorB] - Local position of the anchor point on the second body. * @property {b2Vec2} [axisA] - The local axis for the joint movement on body A. * @property {b2Vec2} [axisB] - The local axis for the joint movement on body B. * @property {boolean} [enableMotor] - Whether to enable the joint's motor. * @property {number} [maxMotorTorque] - The maximum torque the motor can apply. * @property {number} [motorSpeed] - The desired motor speed. * @property {boolean} [collideConnected] - Whether the connected bodies should collide. */ /** * Creates a wheel joint between two bodies. * @param {WheelJointConfig} data - Configuration for the wheel joint. * @returns {{jointId: b2JointId}} The ID of the created wheel joint. */ export function CreateWheelJoint(data) ``` -------------------------------- ### CreatePrismaticJoint Example Source: https://github.com/phaserjs/phaser-box2d/blob/main/README.md Configuration and creation of a prismatic joint between two bodies. ```javascript /** * @typedef {Object} PrismaticJointConfig * @property {b2WorldId} worldId - ID for the world in which the bodies and joint exist. * @property {b2PrismaticJointDef} [jointDef] - A pre-existing b2PrismaticJointDef. * @property {b2BodyId} bodyIdA - The first body to connect with this joint. * @property {b2BodyId} bodyIdB - The second body to connect with this joint. * @property {b2Vec2} [anchorA] - Local position of the anchor point on the first body. * @property {b2Vec2} [anchorB] - Local position of the anchor point on the second body. * @property {b2Vec2} [axis] - The local axis for the joint movement on body A. * @property {number} [referenceAngle] - The reference angle between the bodies. * @property {boolean} [enableSpring] - Whether to enable the joint's spring. * @property {number} [hertz] - The frequency of the joint's spring. * @property {number} [dampingRatio] - The damping ratio of the joint's spring. * @property {boolean} [enableLimit] - Whether to enable translation limits. * @property {number} [lowerTranslation] - The lower translation limit. * @property {number} [upperTranslation] - The upper translation limit. * @property {boolean} [enableMotor] - Whether to enable the joint's motor. * @property {number} [maxMotorForce] - The maximum force the motor can apply. * @property {number} [motorSpeed] - The desired motor speed. * @property {boolean} [collideConnected] - Whether the connected bodies should collide. */ /** * Creates a prismatic joint between two bodies. * @param {PrismaticJointConfig} data - Configuration for the prismatic joint. * @returns {{jointId: b2JointId}} The ID of the created prismatic joint. */ export function CreatePrismaticJoint(data) ``` -------------------------------- ### Running API Docs Source: https://github.com/phaserjs/phaser-box2d/blob/main/README.md Instructions on how to run the API Docs site server. ```bash npm install npm run docs ``` -------------------------------- ### Creating the Ground Body Source: https://github.com/phaserjs/phaser-box2d/blob/main/getting-started/GETTING-STARTED.md Code to create a static rectangular ground body with a slight slope. ```js import { b2DefaultBodyDef, b2Rot, CreateBoxPolygon, b2BodyType, b2HexColor } from '../lib/PhaserBox2D.js'; const groundBodyDef = b2DefaultBodyDef(); groundBodyDef.rotation = new b2Rot(Math.cos(Math.PI * .03), Math.sin(Math.PI * .03)); const ground = CreateBoxPolygon({ worldId: world.worldId, type: b2BodyType.b2_staticBody, bodyDef: groundBodyDef, position: new b2Vec2(0, -6), size: new b2Vec2(20, 1), density: 1.0, friction: 0.5, color: b2HexColor.b2_colorLawnGreen }); ``` -------------------------------- ### Create a Phaser Sprite Source: https://github.com/phaserjs/phaser-box2d/blob/main/getting-started/GETTING-STARTED.md Creates a regular Phaser sprite with specified position, texture, rotation, and scale. ```javascript const platform = this.add.sprite(640, 600, 'platform').setRotation(0.06).setScale(1.5); ``` -------------------------------- ### Update Function for Simulation and Rendering Source: https://github.com/phaserjs/phaser-box2d/blob/main/getting-started/GETTING-STARTED.md The update function called by RequestAnimationFrame to step the simulation and render the world. ```js function update (deltaTime) { WorldStep({ worldId: world.worldId, deltaTime: deltaTime }); ctx.clearRect(0, 0, canvas.width, canvas.height); b2World_Draw(world.worldId, m_draw); } ``` -------------------------------- ### Wrapper Functions Example Source: https://github.com/phaserjs/phaser-box2d/blob/main/README.md Demonstrates the use of wrapper functions for creating worlds and boxes. ```javascript let world = CreateWorld({ worldDef: b2DefaultWorldDef() }); let box = CreateBoxPolygon({ worldId: world.worldId, bodyDef: b2DefaultBodyDef(), type: b2BodyType.b2_dynamicBody, position: new b2Vec2(0, 4), size: 1, density: 1.0, friction: 0.3 }); ``` -------------------------------- ### Phaser Debug Draw Initialization Source: https://github.com/phaserjs/phaser-box2d/blob/main/getting-started/GETTING-STARTED.md Initializes the PhaserDebugDraw object to render the Box2D world in the Phaser scene. ```javascript this.worldDraw = new PhaserDebugDraw(debug, 1280, 720, GetWorldScale()); ``` -------------------------------- ### Convert Sprite to Static Box Body Source: https://github.com/phaserjs/phaser-box2d/blob/main/getting-started/GETTING-STARTED.md Converts a Phaser sprite into a static Box2D body with specified friction. ```javascript SpriteToBox(worldId, platform, { type: STATIC, friction: 0.1 }); ``` -------------------------------- ### Importing Functions Source: https://github.com/phaserjs/phaser-box2d/blob/main/README.md Demonstrates how to import specific functions from the physics.js file. ```javascript import { CreateWorld } from 'physics.js'; ``` -------------------------------- ### Convert Sprite to Dynamic Box Body Source: https://github.com/phaserjs/phaser-box2d/blob/main/getting-started/GETTING-STARTED.md Converts a Phaser sprite into a dynamic Box2D body with specified restitution and friction. ```javascript const block = this.add.sprite(640, 90, 'block'); const box = SpriteToBox(worldId, block, { restitution: 0.7, friction: 0.1 }); AddSpriteToWorld(worldId, block, box); ```