Convert Figma logo to code with AI

schteppe logop2.js

JavaScript 2D physics library

2,639
330
2,639
105

Top Related Projects

3,047

Lightweight 3d physics engine for javascript

16,610

a 2D rigid body physics engine for the web ▲● ■

Port of Box2D to JavaScript using Emscripten

2D JavaScript Physics Engine

A modular, extendable, and easy-to-use physics engine for javascript

💣 A lightweight 3D physics engine written in JavaScript.

Quick Overview

p2.js is a 2D physics engine for JavaScript, designed for use in games and simulations. It provides a robust set of tools for simulating rigid body dynamics, including collision detection and response, constraints, and various shapes.

Pros

  • Lightweight and fast, suitable for real-time applications
  • Supports various shapes and constraints for complex simulations
  • Well-documented with examples and API reference
  • Active community and ongoing development

Cons

  • Limited to 2D physics, not suitable for 3D simulations
  • May require additional libraries for rendering and input handling
  • Performance can degrade with a large number of bodies or complex interactions
  • Learning curve for advanced features and optimizations

Code Examples

Creating a world and adding a circle:

const world = new p2.World({ gravity: [0, -9.82] });
const circleBody = new p2.Body({
  mass: 5,
  position: [0, 10],
});
const circleShape = new p2.Circle({ radius: 1 });
circleBody.addShape(circleShape);
world.addBody(circleBody);

Adding a ground plane:

const groundBody = new p2.Body({
  mass: 0,
  position: [0, -1],
});
const groundShape = new p2.Plane();
groundBody.addShape(groundShape);
world.addBody(groundBody);

Stepping the simulation:

const fixedTimeStep = 1 / 60;
const maxSubSteps = 10;

function animate(time) {
  requestAnimationFrame(animate);
  world.step(fixedTimeStep, time - lastTime, maxSubSteps);
  lastTime = time;
  // Update rendering here
}

let lastTime;
requestAnimationFrame(animate);

Getting Started

  1. Install p2.js using npm:

    npm install p2
    
  2. Import p2.js in your project:

    import * as p2 from 'p2';
    
  3. Create a world and add bodies:

    const world = new p2.World({ gravity: [0, -9.82] });
    const body = new p2.Body({ mass: 1, position: [0, 5] });
    const shape = new p2.Circle({ radius: 1 });
    body.addShape(shape);
    world.addBody(body);
    
  4. Step the simulation in your game loop:

    world.step(1/60);
    
  5. Update your rendering based on the body positions and rotations.

Competitor Comparisons

3,047

Lightweight 3d physics engine for javascript

Pros of Oimo.js

  • 3D physics engine, offering more complex simulations than p2.js's 2D focus
  • Designed for use with Three.js, providing seamless integration for 3D web graphics
  • Supports a wider range of shapes and constraints for 3D environments

Cons of Oimo.js

  • Less active development and community support compared to p2.js
  • May have higher performance overhead due to 3D calculations
  • Documentation is less comprehensive than p2.js

Code Comparison

Oimo.js (3D physics):

var world = new OIMO.World({ 
    timestep: 1/60, 
    iterations: 8, 
    broadphase: 2,
    worldscale: 1,
    random: true,
    info: false
});

p2.js (2D physics):

var world = new p2.World({
    gravity: [0, -9.82]
});
world.defaultContactMaterial.friction = 0.3;

Both libraries offer easy-to-use APIs for creating physics simulations, but their focus (3D vs 2D) and integration with graphics libraries differ. Oimo.js is better suited for 3D web applications, especially those using Three.js, while p2.js excels in 2D simulations with broader platform support and more active development.

16,610

a 2D rigid body physics engine for the web ▲● ■

Pros of Matter.js

  • More active development and maintenance
  • Extensive documentation and examples
  • Better performance for complex simulations

Cons of Matter.js

  • Larger file size and potentially higher memory usage
  • Less suitable for mobile devices due to performance overhead

Code Comparison

Matter.js:

var engine = Matter.Engine.create();
var world = engine.world;
var box = Matter.Bodies.rectangle(200, 200, 80, 80);
Matter.World.add(world, box);
Matter.Engine.run(engine);

p2.js:

var world = new p2.World();
var boxShape = new p2.Box({ width: 1, height: 1 });
var boxBody = new p2.Body({ mass: 1, position: [0, 0] });
boxBody.addShape(boxShape);
world.addBody(boxBody);

Both libraries offer 2D physics simulations for JavaScript applications. Matter.js provides a more comprehensive set of features and better documentation, making it easier for beginners to get started. However, p2.js is more lightweight and may be preferable for simpler projects or mobile applications where performance is crucial. The code comparison shows that Matter.js has a more intuitive API, while p2.js requires more setup but offers finer control over physics objects.

Port of Box2D to JavaScript using Emscripten

Pros of box2d.js

  • More mature and widely used physics engine, ported from the popular C++ Box2D library
  • Offers a broader range of features and more complex physics simulations
  • Better documentation and community support due to its larger user base

Cons of box2d.js

  • Larger file size and potentially higher performance overhead
  • Steeper learning curve, especially for developers new to physics engines
  • Less flexibility for customization compared to p2.js

Code Comparison

p2.js:

var world = new p2.World({
    gravity: [0, -9.82]
});
var boxShape = new p2.Box({ width: 1, height: 1 });
var boxBody = new p2.Body({ mass: 1, position: [0, 5] });
boxBody.addShape(boxShape);
world.addBody(boxBody);

box2d.js:

var world = new b2World(new b2Vec2(0, -9.8));
var bodyDef = new b2BodyDef();
bodyDef.type = b2Body.b2_dynamicBody;
bodyDef.position.Set(0, 5);
var body = world.CreateBody(bodyDef);
var shape = new b2PolygonShape();
shape.SetAsBox(0.5, 0.5);
body.CreateFixture(shape, 1.0);

Both libraries offer 2D physics simulations, but p2.js focuses on simplicity and ease of use, while box2d.js provides more advanced features at the cost of complexity. The choice between them depends on the specific requirements of your project and your familiarity with physics engines.

2D JavaScript Physics Engine

Pros of planck.js

  • Better performance, especially for complex simulations
  • More actively maintained with regular updates
  • Closer to Box2D API, making it easier for developers familiar with Box2D

Cons of planck.js

  • Slightly steeper learning curve for beginners
  • Less extensive documentation compared to p2.js
  • Smaller community and fewer resources available online

Code Comparison

p2.js:

var world = new p2.World({
    gravity: [0, -9.82]
});
var boxShape = new p2.Box({ width: 1, height: 1 });
var boxBody = new p2.Body({
    mass: 1,
    position: [0, 5],
    angularVelocity: 1
});

planck.js:

var world = planck.World({
    gravity: planck.Vec2(0, -9.81)
});
var boxShape = planck.Box(0.5, 0.5);
var boxBody = world.createDynamicBody({
    position: planck.Vec2(0, 5),
    angularVelocity: 1
});

Both libraries offer 2D physics simulations for JavaScript, but planck.js provides better performance and is more actively maintained. However, p2.js may be easier for beginners to learn and has more extensive documentation available.

A modular, extendable, and easy-to-use physics engine for javascript

Pros of PhysicsJS

  • More extensive documentation and examples
  • Supports a wider range of physics simulations, including soft-body physics
  • Modular architecture allows for easy customization and extension

Cons of PhysicsJS

  • Generally slower performance compared to p2.js
  • Less active development and community support
  • Steeper learning curve for beginners

Code Comparison

PhysicsJS:

var world = Physics();
var box = Physics.body('rectangle', {
    x: 50,
    y: 30,
    width: 50,
    height: 50
});
world.add(box);

p2.js:

var world = new p2.World();
var boxShape = new p2.Box({ width: 1, height: 1 });
var boxBody = new p2.Body({
    mass: 1,
    position: [0, 0],
    shape: boxShape
});
world.addBody(boxBody);

Both libraries offer similar functionality for creating physics simulations, but their syntax and approach differ. PhysicsJS uses a more object-oriented style with a focus on modularity, while p2.js employs a more direct approach to creating and managing physics objects. The choice between the two depends on specific project requirements, performance needs, and developer preferences.

💣 A lightweight 3D physics engine written in JavaScript.

Pros of cannon-es

  • More active development and maintenance
  • Better TypeScript support and modern JavaScript features
  • Improved performance and optimizations

Cons of cannon-es

  • Less extensive documentation compared to p2.js
  • Smaller community and fewer resources available
  • Some API changes may require migration efforts for existing p2.js projects

Code Comparison

p2.js:

var world = new p2.World({
    gravity: [0, -9.82]
});
var boxShape = new p2.Box({ width: 1, height: 1 });
var boxBody = new p2.Body({
    mass: 1,
    position: [0, 5],
    shape: boxShape
});
world.addBody(boxBody);

cannon-es:

const world = new CANNON.World({
    gravity: new CANNON.Vec3(0, -9.82, 0)
});
const boxShape = new CANNON.Box(new CANNON.Vec3(0.5, 0.5, 0.5));
const boxBody = new CANNON.Body({
    mass: 1,
    position: new CANNON.Vec3(0, 5, 0),
    shape: boxShape
});
world.addBody(boxBody);

Both libraries offer similar functionality for 2D physics simulations, but cannon-es provides better support for 3D physics and modern JavaScript environments. The code structure is similar, with minor differences in syntax and object creation.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

p2.js

2D rigid body physics engine written in JavaScript. Includes collision detection, contacts, friction, restitution, motors, springs, advanced constraints and various shape types.

Demos | Examples | Documentation | Download | CDN | Wiki

Featured projects using p2.js

Demos

These demos use the p2 Demo framework, which provides rendering and interactivity. Use mouse/touch to throw or create objects. Use the right menu (or console!) to tweak parameters. Or just check the source to see how to programmatically build the current scene using p2.

Examples

Examples showing how to use p2.js with your favorite renderer.

Sample code

The following example uses the World, Circle, Body and Plane classes to set up a simple physics scene with a ball on a plane.

// Create a physics world, where bodies and constraints live
var world = new p2.World({
    gravity:[0, -9.82]
});

// Create an empty dynamic body
var circleBody = new p2.Body({
    mass: 5,
    position: [0, 10]
});

// Add a circle shape to the body
var circleShape = new p2.Circle({ radius: 1 });
circleBody.addShape(circleShape);

// ...and add the body to the world.
// If we don't add it to the world, it won't be simulated.
world.addBody(circleBody);

// Create an infinite ground plane body
var groundBody = new p2.Body({
    mass: 0 // Setting mass to 0 makes it static
});
var groundShape = new p2.Plane();
groundBody.addShape(groundShape);
world.addBody(groundBody);

// To animate the bodies, we must step the world forward in time, using a fixed time step size.
// The World will run substeps and interpolate automatically for us, to get smooth animation.
var fixedTimeStep = 1 / 60; // seconds
var maxSubSteps = 10; // Max sub steps to catch up with the wall clock
var lastTime;

// Animation loop
function animate(time){
	requestAnimationFrame(animate);

    // Compute elapsed time since last render frame
    var deltaTime = lastTime ? (time - lastTime) / 1000 : 0;

    // Move bodies forward in time
    world.step(fixedTimeStep, deltaTime, maxSubSteps);

    // Render the circle at the current interpolated position
    renderCircleAtPosition(circleBody.interpolatedPosition);

    lastTime = time;
}

// Start the animation loop
requestAnimationFrame(animate);

To interact with bodies, you need to do it after each internal step. Simply attach a "postStep" listener to the world, and make sure to use body.position here - body.interpolatedPosition is only for rendering.

world.on('postStep', function(event){
    // Add horizontal spring force
    circleBody.force[0] -= 100 * circleBody.position[0];
});

Install

Browser

Download either p2.js or the minified p2.min.js and include the script in your HTML:

<script src="p2.js" type="text/javascript"></script>

If you would like to use ordinary Array instead of Float32Array, define P2_ARRAY_TYPE globally before loading the library.

<script type="text/javascript">P2_ARRAY_TYPE = Array;</script>
<script src="p2.js" type="text/javascript"></script>
Node.js
npm install p2

Then require it like so:

var p2 = require('p2');

Supported collision pairs

CirclePlaneBoxConvexParticleLineCapsuleHeightfieldRay
CircleYes--------
PlaneYes--------
BoxYesYesYes------
ConvexYesYesYesYes-----
ParticleYesYesYesYes-----
LineYesYes(todo)(todo)-----
CapsuleYesYesYesYesYes(todo)Yes--
HeightfieldYes-YesYes(todo)(todo)(todo)--
RayYesYesYesYes-YesYesYes-

Note that concave polygon shapes can be created using Body.fromPolygon.

Install

Make sure you have git, Node.js, NPM and grunt installed.

git clone https://github.com/schteppe/p2.js.git;
cd p2.js;
npm install; # Install dependencies
grunt;

Grunt tasks

List all tasks using grunt --help.

grunt        # Run tests, build, minify
grunt dev    # Run tests, build
grunt test   # Run tests
grunt yuidoc # Build docs
grunt watch  # Watch for changes and run the "dev" task

Release process

  1. Bump version number.
  2. Build and commit files in build/ and docs/.
  3. Tag the commit with the version number e.g. vX.Y.Z
  4. Add relase notes to github
  5. Publish to NPM

NPM DownloadsLast 30 Days