Fishrock123 / p2.js

JavaScript 2D physics library

Home Page:http://schteppe.github.com/p2.js/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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

Demos

Examples

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

More examples coming soon.

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.

// Setup our world
var world = new p2.World({ gravity:[0,-9.82] });

// Create a circle
var radius = 1,
    circleShape = new p2.Circle(radius),
    circleBody = new p2.Body({ mass:5, position:[0,10] });
circleBody.addShape(circleShape);

// Create a plane
var groundShape = new p2.Plane(),
    groundBody = new p2.Body({ mass:0 });
groundBody.addShape(groundShape);

// Add the bodies to the world
world.addBody(circleBody);
world.addBody(groundBody);

// Step the simulation
setInterval(function(){
    world.step(1.0/60.0);
    console.log("Circle y position: " + circleBody.position[1]);
}, 1000.0/60.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 GLMAT_ARRAY_TYPE globally before loading the library.

<script type="text/javascript">GLMAT_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 Rectangle Convex Particle Line Capsule Heightfield
Circle Yes Yes Yes Yes Yes Yes Yes Yes
Plane - - Yes Yes Yes Yes Yes -
Rectangle - - Yes Yes Yes (todo) Yes Yes
Convex - - - Yes Yes (todo) Yes Yes
Particle - - - - - - Yes (todo)
Line - - - - - (todo) (todo) (todo)
Capsule - - - - - - Yes (todo)
Heightfield - - - - - - - -

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

Unit testing

Tests are written for Nodeunit. Run the tests with the command grunt test.

Contribute

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

git clone https://github.com/schteppe/p2.js.git; # Clone the repo
cd p2.js;
npm install;                                     # Install dependencies
                                                 # (make changes to source)
grunt;                                           # Builds build/p2.js and build/p2.min.js

The most recent commits are currently pushed to the master branch. Thanks for contributing!

About

JavaScript 2D physics library

http://schteppe.github.com/p2.js/

License:Other


Languages

Language:JavaScript 97.8%Language:CSS 2.2%