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
- Car
- Circle container
- Collision tests
- Compound objects
- Concave objects
- Constraints
- Fixed rotation
- Friction
- Gear constraint
- Heightfield
- Island solver
- Lock constraint
- Piston
- Prismatic constraint
- Ragdoll
- Sensor
- Restitution
- Sleep
- Springs
- Tearable constraints
- Surface velocity
- Suspension
Examples showing how to use p2.js with your favorite renderer.
More examples coming soon.
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);
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>
Until the code gets somewhat more stable, use the git url to install:
npm install git://github.com/schteppe/p2.js
Or add the dependency to your package.json
:
...
"dependencies" : {
"p2" : "git://github.com/schteppe/p2.js"
}
...
Then require it like so:
var p2 = require('p2');
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 | (todo) |
Convex | - | - | - | Yes | Yes | (todo) | Yes | (todo) |
Particle | - | - | - | - | - | - | Yes | (todo) |
Line | - | - | - | - | - | (todo) | (todo) | (todo) |
Capsule | - | - | - | - | - | - | Yes | (todo) |
Heightfield | - | - | - | - | - | - | - | - |
Note that concave polygon shapes can be created using Body.fromPolygon.
Tests are written for Nodeunit. Run the tests with the command grunt test
.
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!
- Added property
.enableIslandSleeping
toWorld
. - Added property
.useFrictionGravityOnZeroGravity
toWorld
. - Renamed
.useWorldGravityForFrictionApproximation
inWorld
to.useWorldGravityAsFrictionGravity
to keep things more uniform. - Sleep improvements.
- Added property
.frictionIterations
toGSSolver
, and removed.skipFrictionIterations
. - Upgraded to gl-matrix
2.1.0
. - Removed
QuadTree
. - Removed
mat2
. - Added
Utils.extend
. - Added methods
.setStiffness
and.setRelaxation
methods toConstraint
. - Removed properties
.stiffness
,.relaxation
and.useGlobalEquationParameters
fromGSSolver
. - Added methods
.setGlobalStiffness
,.setGlobalRelaxation
,.setGlobalEquationParameters
toWorld
. - Renamed property
.eps
to.epsilon
forEquation
. - Removed property
.useBoundingBoxes
fromNaiveBroadphase
in favor of the new property.boundingVolumeType
inBroadphase
. - Added methods
.getMaxForce
and.setMaxForce
toLockConstraint
. - Changed property names
.bi
,.bj
,.ni
,.ri
,.rj
to.bodyA
,.bodyB
,.normalA
,.contactPointA
,.contactPointB
inEquation
,ContactEquation
andFrictionEquation
classes. - Removed
IslandSolver
in favor of the new propertyWorld.islandSplit
. - Changed constructors of the
Constraints
so they all take anoptions
object as last parameter. - Added property
.collideConnected
toConstraint
. - Added property
.islandSplit
toWorld
. - Added methods
.disableBodyCollision
and.enableBodyCollision
toWorld
. - Added properties
.useWorldGravityForFrictionApproximation
and.frictionGravity
toWorld
. - Added
Heightfield
class. - Removed properties
.defaultFriction
and.defaultRestitution
fromWorld
, in favor of.defaultContactMaterial
. - Added property
.enabled
toEquation
. - Added property
.surfaceVelocity
toContactMaterial
. - Added property
.sensor
toShape
. World
now emits events'beginContact'
,'endContact'
and'preSolve'
.- Added property
.gravityScale
toBody
. - Renamed class
SAP1DBroadphase
toSAPBroadphase
. - Added property
.interpolatedPosition
to ``Body```. - Added method
.internalStep
toWorld
. - Added property
.applyGravity
toWorld
. - Renamed method
.computeC
to.computeInvC
inEquation
, and made it compute the inverse. - Added static method
Utils.splice
. - Added property
.world
toBody
. - Added property
.fixedRotation
toBody
. - Added class
AABB
. - Added properties
.aabb
and.aabbNeedsUpdate
toBody
, as well as a method.updateAABB
. - Added property
.useBoundingBoxes
toNaiveBroadphase
. - Added static method
Broadphase.aabbCheck
. - Added method
.computeAABB
toShape
. - Added static method
Broadphase.canCollide
. Body
now inherits fromEventEmitter
, and dispatches events'sleep'
,'sleepy'
and'wakeup'
.- Added properties
.allowSleep
,.sleepState
,.sleepSpeedLimit
,.sleepTimeLimit
,.lastTimeSleepy
as well as methods.sleep
,.wakeUp
and.sleepTick
toBody
. - Added enums
Body.AWAKE
,Body.SLEEPY
,Body.SLEEPING
. - Added property
.enableBodySleeping
toWorld
. - Added options
.disableRotationalLock
,.lowerLimit
,.upperLimit
toPrismaticConstraint
constructor. - Added methods
.enableMotor
,.disableMotor
toPrismaticConstraint
as well as properties.motorEnabled
,.motorSpeed
,.motorEquation
.
- Added properties
.damping
and.angularDamping
toBody
. - Added property
.applyDamping
toWorld
. - Added properties
.shapeA
and.shapeB
toContactEquation
andFrictionEquation
. - Added property
.contactEquation
toFrictionEquation
. - Added property
.multiplier
toEquation
. - Added properties
.lowerLimitEnabled
,.lowerLimit
,.upperLimitEnabled
,.upperLimit
toRevoluteConstraint
. - Added property
.frictionCoefficient
toFrictionEquation
andNarrowphase
. The solver now updates the friction force bounds dynamically in the solver from this value.FrictionEquation.setSlipForce()
is thus deprecated. - Changed name of
Narrowphase.convexPlane
toNarrowphase.planeConvex
. - Changed name of
Narrowphase.capsulePlane
toNarrowphase.planeCapsule
. - Added property
.emitImpactEvent
toWorld
. - Added method
.getBodyById
toWorld
. - Added property
.skipFrictionIterations
toGSSolver
. - Changed parameter names for
PrismaticConstraint
. This breaks backwards compatibility. - Added properties
.localAxisA
,.localAnchorA
,.localAnchorB
, toPrismaticConstraint
.
- Added method
Narrowphase.prototype.collidedLastStep
- Added property
.firstImpact
toContactEquation
and changed the way it handles restitution. Solver
now inherits fromEventEmitter
.IslandSolver
now emits a'beforeSolveIsland'
event.- Added method
Solver.prototype.sortEquations
and property.equationSortFunction
. - Added class
LockConstraint
. - Added property
.time
toWorld
. World
now emits'impact'
event.- Added property
Utils.ARRAY_TYPE
.
- Added
Utils
- The returned array by
Broadphase.prototype.getCollisionPairs
is now reused in between calls. - Added method
.addEquations
toSolver
to faster add an array ofEquation
s. - Added method
.updateArea
and property.area
to Shape - Added methods
.adjustCenterOfMass
and.fromPolygon
toBody
. - Renamed
Nearphase
toNarrowphase
. - Added methods
.upgradeJSON
,.runNarrowphase
and.integrateBody
toWorld
. - Renamed
PointToPointConstraint
toRevoluteConstraint
. - Added static method
GSSolver.iterateEquation
. - Added methods
.addConstraintVelocity
,.resetConstraintVelocity
,.setZeroForce
toBody
. - Added static method
SAP1DBroadphase.checkBounds
. body.shapeOffsets
and.shapeAngles
may now only be vectors and numbers.
- Removed
World.collidingBodies
sinceWorld.bodies
can be used equivalently. - Added property
DistanceConstraint.distance
- Added contact response between a lot of Shape types. Check table above.
- Added friction for most of the contact types
- Added
PointToPointConstraint
- Added
Line
- Added method
Shape.computeMomentOfInertia
- Added method
Body.updateMassProperties
- Removed
mat2
as it is not needed inside the library for now. - Changed
Shape
usage. AShape
is now added to aBody
viaBody.addShape(shape,offset,angle)
. - Removed
Body.shape
, addedBody.shapes
,.shapeOffsets
,.shapeAngles
- Added
Rectangle
- Added method
Convex.updateTriangles
- Added method
Convex.updateCenterOfMass
- Fixed
Convex.computeMomentOfInertia
, now it should be correct. - Updated the Node.js API so that each class is required using the pattern
var ClassName = require('./ClassName')
instead ofvar ClassName = require('./ClassName').ClassName
- Added
Nearphase
class - Removed
World.contacts
and.frictionEquations
in favor ofWorld.nearphase.contactEquations
andWorld.nearphase.frictionEquations
- Added
Capsule
class - Added
Spring
properties.localAnchorA
,.localAnchorB
. - Added
Spring
methods.getWorldAnchorA
,.setWorldAnchorA
and the corresponding for B. - Added
p2.version
for browser. - Added
PrismaticConstraint
. - Added properties
.collisionGroup
and.collisionMask
toShape
. This enables collision filtering. - Added method
World.hitTest
. - Renamed equation properties
.k
and.d
ofEquation
andGSSolver
to.stiffness
and.relaxation
, respectively. Removed properties.a
,.b
,.eps
from both and instead compute them on the fly in the solver. - Added property
GSSolver.useGlobalEquationParameters
so that it is possible to turn on and off per-equation solver settings (.stiffness
and.relaxation
). - Removed
Broadphase.<shapeTypeA><shapeTypeB>
since they are not used in any broadphase implementation any more. - Added experimental
QuadTree
broadphase. - Added
SAP1DBroadphase
- Renamed
World.friction
toWorld.defaultFriction
- Added class
RotationalVelocityEquation
- Added methods
.enableMotor
,.disableMotor
,.setMotorSpeed
toPointToPointConstraint
- Added
EventEmitter
World
now emits the following events:'postStep'
,'addBody'
,'addSpring'
- Moved properties of
Body.MotionState
toBody
. Usage is nowBody.STATIC
,Body.DYNAMIC
,Body.KINEMATIC
. - Removed asynchronous behaviour of
World.step()
.