• Stars
    star
    2,607
  • Rank 16,919 (Top 0.4 %)
  • Language
    JavaScript
  • License
    Other
  • Created over 11 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

JavaScript 2D physics library

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

Circle Plane Box Convex Particle Line Capsule Heightfield Ray
Circle Yes - - - - - - - -
Plane Yes - - - - - - - -
Box Yes Yes Yes - - - - - -
Convex Yes Yes Yes Yes - - - - -
Particle Yes Yes Yes Yes - - - - -
Line Yes Yes (todo) (todo) - - - - -
Capsule Yes Yes Yes Yes Yes (todo) Yes - -
Heightfield Yes - Yes Yes (todo) (todo) (todo) - -
Ray Yes Yes Yes Yes - Yes Yes Yes -

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

More Repositories

1

cannon.js

A lightweight 3D physics engine written in JavaScript.
JavaScript
4,584
star
2

poly-decomp.js

Decompose 2D polygons into convex pieces.
JavaScript
416
star
3

gpu-physics.js

GPGPU physics for Three.js
JavaScript
280
star
4

ammo.js-demos

Demo application base class and 3D physics demos based on ammo.js. Support for several scenegraphs including Three.js and SceneJS.
JavaScript
114
star
5

imgui-wasm

imgui/wasm boilerplate
C++
42
star
6

cartridge.js

HTML5 retro game engine
JavaScript
38
star
7

codegif

Use Canvas API to make a gif animation
JavaScript
36
star
8

motionblur

WebGL shader effect
JavaScript
34
star
9

remote-physics

A node.js app that runs a physics engine and lets clients download physics data in real time.
JavaScript
24
star
10

occlusion-culling.js

Occlusion culling tests using three.js
JavaScript
20
star
11

vehicle-editor

A goofy vehicle editor made using Cannon.js physics and Goo Create.
JavaScript
19
star
12

floatcompress.js

Simple library for doing lossy compress of floats. Can be used to pack floats into a typed array when high precision is not needed.
JavaScript
16
star
13

goo-cannon-softbody

Experimenting with soft body simulation using Cannon.js in Goo Create
JavaScript
16
star
14

physicstoy

2D physics editor
JavaScript
12
star
15

voronoi-cube

Exploding cube in WebGL/GooEngine using 3D Voronoi tessellation data. (Goofy Day project)
JavaScript
12
star
16

sweep-and-prune

2D collision detection for AABBs
HTML
11
star
17

doc.js

Web based on-the-fly documentation generator targeted for JavaScript.
JavaScript
11
star
18

gpu-springs

GPU accelerated spring simulation
JavaScript
9
star
19

smart-signal-routing

Orthogonal connector routing for use in interactive diagram editors
JavaScript
8
star
20

m.js

JavaScript matrix math library that uses typed arrays.
JavaScript
7
star
21

velvet-drop

GPU cloth simulation (a.k.a Velvet Drop) made in Goo Create
JavaScript
6
star
22

tinygoon

8-bit style WebGL multiplayer game using the GamePad API
JavaScript
5
star
23

CreateForge

Visual shader editor for Goo Engine
HTML
5
star
24

dansa

Dance game for the web
JavaScript
5
star
25

taptruck

Mobile 2D WebGL game. Drive the truck to the goal without tipping over.
JavaScript
5
star
26

jox

Source code documentation generator for JavaScript
JavaScript
5
star
27

hyper-cube

Spinning Cube made with Goo Create
JavaScript
4
star
28

goo-p2-platformer

Simple physics based platformer scene built using Goo Create and engine.
JavaScript
4
star
29

refract

2D WebGL puzzle game. Guide the laser beam to the goal.
JavaScript
4
star
30

goo-bunnymark

Tribute to Pixi.js bunnymark. This time in 3D, made with Goo Engine.
HTML
3
star
31

multibody-xml

An XML markup language for descibing a physical multibody system.
3
star
32

bomb-sorting-game

Sort the boxes into their containers!
JavaScript
3
star
33

fuffrboxing

3D WebGL mobile game made for Fuffr
JavaScript
2
star
34

schteppe.github.com

2
star
35

node-mysql-querycache

Query caching to relax your MySQL database. Layer on top of node-mysql.
JavaScript
1
star
36

wasm_test

WebAssembly
1
star
37

ragdoll-goon

Almost-working goofy project. Need to be fixed!
JavaScript
1
star
38

goon-yoga

Yoga for the Goon. Built with Goo Engine.
JavaScript
1
star
39

fb-node-issues

Public Issue tracker
1
star