JavaScript 2D physics library

Overview

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
Comments
  • Vectors and Matrices should be refactored.

    Vectors and Matrices should be refactored.

    Is any reason for tVec2.create() vs new tVec2()?

    Regardless, tVec.set(o, x, y) is kind if silly and we should make a prototype method for functions like it so that we can call (vec).set(x, y).

    If in doubt, the old methods can be kept for internal use, and the new ones can be added for the API.

    opened by Fishrock123 40
  • ccd Problem

    ccd Problem

    Attached are gifs that show the problem WITH and WITHOUT ccdSpeedThreshold set.

    Simply uncommenting the ccdSpeedThreshold variable yields really weird results.

    body = new Body({
      position: bullet.position,
      angle: bullet.angle,
      //ccdSpeedThreshold: this.initialBulletSpeed * 0.4,
      angularDamping: 1,
      mass: 5,
      damping: 0.01,
      velocity: [
        this.initialBulletSpeed * Math.cos(bullet.angle),
        this.initialBulletSpeed * Math.sin(bullet.angle)
      ]
    });
    shape = new Circle({
      radius: 4,
      collisionGroup: CollisionGroups.BULLETS,
      collisionMask: CollisionGroups.ENEMIES | CollisionGroups.TERRAIN
    });
    body.addShape(shape);
    world.addBody(body);
    

    No ccd:

    No ccd

    ccd turned on: ccd on

    ccd on with arc bullet positions: ccd on with arc bullet positions

    The visual shows the small round bullets being fired from the player position fired at an invisible plane wall. I was hoping that I could use ccd for bullets because they are visually entering the boxes, sometimes for two whole frames. It's visually unappealing, but not game breaking.

    Any workarounds/help?

    Thank you for your excellent JS library.

    opened by jtenner 37
  • Is p2 abandoned?

    Is p2 abandoned?

    Is p2 abandoned?

    I've found some functions like runNarrowphase to be global instead in World class scope. It looks like mess and it's the master branch. Why?

    opened by Kamil93 17
  • Determinism of the system

    Determinism of the system

    Hi,

    I am using p2.js version v0.6.1 for a multiplayer game which runs in node.js on the server and in a browser on the client. I am running a physic simulation on the server and on the client.

    I was trying to see the extent of the differences of running the "same" simulation on the server and on the client. I setup identical worlds (as far as I can tell) and I apply the same force to a circular body that bounces around on planes (limits of the world) and on other circular bodies inside the planes. On collisions, sometimes server and client are getting the exact same results. Some other times, the angle of the collisions varies roughly by as much as approximately 15 degrees (I didn't measure it, it is a visual approximation). I thought the differences would be smaller than that so that I would be able to make small corrections on the clients that would go unnoticed. That is not the case.

    Is is expected behavior or am I doing something wrong (or my worlds are probably not as identical as I think - apart from the environment in which javascript is running that is)?

    Thanks a lot for your time.

    opened by sowee15 14
  • Ball has more momentum than conservation

    Ball has more momentum than conservation

    I put all the forces of the physical world are removed, the interval 100 ms to create a ball, to create a total of 50 teeth, the ball and the wall a few times after the collision angle of reflection and speed some ball has changed several times, the beginning of the collision is correct. With a version of the v0.7.1 p2.js, if you can download the EgretEngine run Demo. download address: http://tool.egret-labs.org/EgretEngine/EgretEngine-v3.1.8.exe?time=1473127114 and http://tool.egret-labs.org/EgretWing/electron/EgretWing-v3.1.8.exe?time=1473127214. EgretEngine's official website is:http://egret.com/

    The setting of this world is:

        //创建world
        this.world = new p2.World();
        //set p2.world.sleepMode
        this.world.sleepMode = p2.World.NO_SLEEPING;
        this.world.applyDamping = false;
        this.world.applyGravity = false;  
        this.world.frictionGravity = 0;
        this.world.applySpringForces = false;
    

    The setting of the ball is:

        var body: p2.Body = new p2.Body({ mass: 3, position: [p2x, p2y],velocity: [-this.speed * Math.sin(angle),       this.speed * Math.cos(angle)] });
        body.type = type;
        body.angularDamping = 0;
        body.angularForce = 0;
        body.applyDamping(0);
        body.allowSleep = true;
        body.damping = 0;
        body.addShape(bodyShape);//给刚体添加p2.Shape
        p2World.addBody(body);
    

    The four sides of the wall is set up:

        var body: p2.Body = new p2.Body({ mass: 1, position: [p2x, p2y]});
        body.type = type;
        body.angularDamping = 0;
        body.angularForce = 0;
        body.applyDamping(0);
        body.allowSleep = false;
        body.damping = 0;
        body.addShape(bodyShape);//给刚体添加p2.Shape
        p2World.addBody(body);
    

    The collision material between the ball and the wall is set up:

        var mtl1: p2.Material = new p2.Material(1000); //The ball
        var mtl2: p2.Material = new p2.Material(1001); //The four sides
        var cmtl: p2.ContactMaterial = new p2.ContactMaterial(mtl1, mtl2, <p2.ContactMaterialOptions>{ restitution: 1.0,  friction: 0 });
        this.world.addContactMaterial(cmtl);
    

    I recorded a video of a ball. http://www.xchang-cq.com/demo/demo.MP4 The demo url: http://www.xchang-cq.com/demo/P2Test.zip

    opened by lcsweet 13
  • Severe FF performance drop down to 0/1FPS with latest p2 build (OverlapKeeper > TupleDictionary)

    Severe FF performance drop down to 0/1FPS with latest p2 build (OverlapKeeper > TupleDictionary)

    Pheewww, another day, another problem finding day :) Sorry to bother you, but I just investigated some hours to find the source for a severe performance drop (down to 1fps, blocks browser) only in firefox.

    The profiler was not so clear about the source- as it mixed up some firefox internal script watchers. But I finally got it: Hello OverlapKeeper! more precisely: Hello TupleDictionary.

    This fiddle: ( it includes a custom build of phaser + p2, latest) http://jsfiddle.net/cfscr/69/

    It doesn't happen with Phaser 2.0.4 (Released version, with a little older version of the overlay keeper) http://jsfiddle.net/cfscr/71/

    And it also does not happen with Phaser 2.0.3 (released version, p2 without the Overlap Keeper). http://jsfiddle.net/cfscr/70/

    And now the MOST WEIRD THING: It only happens with a concatenated file. I mean concatenated not special uglify or whatever applied. Just use one file instead of dozens in the DOM- like I always do in the local environment. That must be the reason why I never found this bug: I always test locally and never tried the compiled/build version in firefox yet.

    //So if I load the scripts like this it happens
    <script src='phaser_and_p2.js'/>
    
    //When I do this instead in the DOM it won't happen ?!?! 
    <script src='phaser/src/file1.js'/>
    <script src='phaser/src/file2.js'/>
    <script src='phaser/src/p2.js'/>
    <script src='phaser/src/and_so_on.js'/>
    

    Attached the two profiler screenshots of the fiddle. You can clearly see when the fiddle window was unfocused or focused again- with that bad performance (the red blocks)

    I use Firefox 28, but it seems to affect newer version as well.

    screen shot 2014-05-10 at 20 32 07 screen shot 2014-05-10 at 20 32 15

    I hope you can reproduce it and I worked on getting it isolated so long. And then the most important question: Any idea?

    Regards George

    opened by georgiee 13
  • Phaser

    Phaser "body.removeShape" triggers error of undefined

    This is just a fast fix but fixed my issue of a shape which gets temporarely added to a body. I guess it triggers this issue (si.position of undefined) when removed but still in loop. Anyhow, there probably is a much better fix but I don't have time to dig deeper. Hope you can have a look at this issue!

    Thanks

    opened by Weedshaker 12
  • fixed plane acts like a bumper when positioned or created above Y of 0

    fixed plane acts like a bumper when positioned or created above Y of 0

    When positioning a 0 mass plane, (ie the the ground) if it is set to a y position above 0 then objects hitting it are bounced up with the force of that y position.

    To see this, load the ragdoll demo and move the ground up.

    do this in the console...

    world.getBodyById(13).position[1]=0.1;

    or if you want it to dance more!

    world.getBodyById(13).position[1]=0.5;

    for any y position below 0 it seems fine.

    opened by ken-sands 11
  • GridBroadphase?

    GridBroadphase?

    Hello,

    Sorry if this is a stupid question, but I can't find the GridBroadphase class anywhere. People reference it here and there, for example: http://paulsalaets.com/posts/selecting-broadphase-p2/

    Was it removed?

    Anyway, I am writing a simple top-down game using threejs as a renderer, but physics will be entirely in 2D. I'd like to have two things:

    • A LOT of objects colliding with each other (namely: projectiles)
    • good physics simulation for actors (enemies and players).

    P2 works perfectly for second, but struggles with first, and I thought GridBroadphase could help.

    In my test setup I have 1000 objects, each with a P2 Body attached, and each body has a basic box shape. World has only gravity enabled and everything else is default; the world being updated 60 times per second.

    Unfortunately, FPS is less than 10 and chrome's profiler is brutal at pointing at the issue: 7800.7 ms | 92.49 % 7805.8 ms | 92.55 % p2.min.js:24 | d.getCollisionPairs

    The broadphase object's "result" array has over million elements, much like it was thinking that everything was colliding with everything. Unfortunately my browser crashes when I try to peek at this array :D

    What can I do to tune P2 for large amount of objects?

    Before I had my own collision detection and its broadphase did manage 60fps on that setup, but it had freezes from time to time which made me go and seek a proper 2d engine :)

    P2 version I am using is the one at current master branch, browser is Chrome 47.0.2526.106 m, OS - Windows 7, CPU - i5 2400, GPU - Radeon 6950 HD 2GB.

    opened by Scharnvirk 10
  • ES6 Modules

    ES6 Modules

    This is a first pass at converting the source to ES6 modules.

    It's still WIP, so tests don't pass yet. I just wanted to see if this was something you were interested in.

    One of the benefits of ES6 modules is that you would be able to do something like this.

    import { Body, World, Circle } from "p2";
    
    var world = new World({ gravity : [0,-10] });
    var body = new Body();
    body.addShape(new Circle(10));
    world.addBody(body);
    

    You can transpile ES6 modules to ES5 using something like square/es6-module-transpiler.

    npm install -g es6-module-transpiler
    compile-modules convert -I src -o build/p2.es6.js src/p2.js
    

    An example of how the output might look is here. https://gist.github.com/timrwood/5f96de256ec9768f70b5

    Using the bundle format from the es6-module-transpiler also has some significant file savings over browserify.

    After some rough tests, it was around half the un-gzipped size of the browserify build and 66% of the gzipped size. I didn't think it was worth comparing exact file sizes until tests are passing and poly-decomp is included.

    Sorry for the brain dump, just wanted to get out all the talking points.

    TODO:

    • [ ] Figure out a solution for importing poly-decomp
    • [ ] Figure out a solution for compiling to common-js for unit testing
    opened by timrwood 10
  • Use pixi.js for rendering

    Use pixi.js for rendering

    The demo renderer should use Pixi.js instead of 2D Three.js. This would be super.

    Don't have time to do this myself at the moment but if someone else want to do it I'd be thankful.

    request 
    opened by schteppe 10
  • Help with resizing P2 Box?

    Help with resizing P2 Box?

    In the demos, I see that the engine will immediately respond to a P2Circle's radius being changed, but I can't seem to replicate the behavior with a P2Box. I've tried changing the height and width and then updating the area, boundingRadius and AABB on the shape as well as the P2Body, but the result always seems to be the original dimensions of the box.

    Is there something I'm missing here, or are you unable to resize a P2Box after it's been added to a body?

    opened by eproasim 0
  • Cannot read property 'overlaps' of undefined

    Cannot read property 'overlaps' of undefined

    Getting this error (seemingly) randomly:

    TypeError: Cannot read property 'overlaps' of undefined
    at Function.Broadphase.aabbCheck (/root/dinogen-mp/node_modules/p2/src/collision/Broadphase.js:92:27)
    at NaiveBroadphase.Broadphase.boundingVolumeCheck (/root/dinogen-mp/node_modules/p2/src/collision/Broadphase.js:110:29)
    at NaiveBroadphase.getCollisionPairs (/root/dinogen-mp/node_modules/p2/src/collision/NaiveBroadphase.js:41:53)
    at World.internalStep (/root/dinogen-mp/node_modules/p2/src/world/World.js:632:29)
    at World.step (/root/dinogen-mp/node_modules/p2/src/world/World.js:543:18)
    

    Any ideas as to what causes this?

    It only happens when using p2 through the npm module, and not with the version included in Phaser 2 CE, which I'm using client side.

    opened by XWILKINX 0
  • Is it possible to use the GPU for better performance?

    Is it possible to use the GPU for better performance?

    Is it possible to use the GPU for better performance? P2.js is very CPU intensive especially when using polygons. Is there some way to use the GPU for some of these calculations, perhaps with GPU.js?

    opened by XWILKINX 0
  • How do I destroy an entity that has a body?

    How do I destroy an entity that has a body?

    Whenever I try I get

    TypeError: Cannot read property 'type' of undefined
        at scriptType.P2World.postUpdate (https://launch.playcanvas.com/api/assets/files/scripts/p2-integration.js?id=40361730&branchId=4ebfaa2e-923e-4ad2-b2e4-d10f0763f57d:170:19)
        at ScriptComponent._scriptMethod (https://code.playcanvas.com/playcanvas-stable.dbg.js:44702:19)
        at ScriptComponent._onPostUpdate (https://code.playcanvas.com/playcanvas-stable.dbg.js:44752:11)
        at ScriptComponentSystem._callComponentMethod (https://code.playcanvas.com/playcanvas-stable.dbg.js:45206:49)
        at ScriptComponentSystem._onPostUpdate (https://code.playcanvas.com/playcanvas-stable.dbg.js:45221:9)
        at Function._helper (https://code.playcanvas.com/playcanvas-stable.dbg.js:29284:12)
        at Function.postUpdate (https://code.playcanvas.com/playcanvas-stable.dbg.js:29304:9)
        at Application.update (https://code.playcanvas.com/playcanvas-stable.dbg.js:50241:20)
        at https://code.playcanvas.com/playcanvas-stable.dbg.js:50847:16
    

    Here's my code to destroy the entity:

    enemyBody.entity.destroy();
    

    The body comes from a collision.

    opened by eoogbe 0
  • How many pixels is a meter in p2.js?

    How many pixels is a meter in p2.js?

    I am developing a game, but cant figure it out, so please i need some koefficient to convert pixels -> meters and meters -> pixel. I am using p2.js with pixi.js v5

    opened by ziarmandhost 3
Releases(v0.7.1)
  • v0.7.1(Nov 21, 2015)

  • v0.7.0(Jul 12, 2015)

    Summary

    • This release makes it more easy and verbose to construct Shapes due to new constructors.
    • Shapes now have position and angle properties, which indicates the local position in the body they are attached to. This also means that a Shape instance can be attached to a single Body.
    • The raycasting API is refactored and should now be more verbose and flexible.
    • TopDownVehicle class was added. Use it to make racing games!

    Changes

    • Renamed Rectangle to Box 380aaa5
    • Updated all Shape constructors so they take their parameters via an options object. This way, Shape constructor parameters can be passed in the same options object. 380aaa5
      • new Rectangle(w, h) => new Box({ width: w, height: h })
      • new Capsule(l, r) => new Capsule({ length: l, radius: r })
      • new Circle(r) => new Circle({ radius: r })
      • new Convex(array) => new Convex({ vertices: array })
      • new Heightfield(array, options) => new Heightfield({ heights: array, [...other options...] })
      • new Line(l) => new Line({ length: l })
    • Removed .shapeOffsets and .shapeAngles from Body in favor of the new .position and .angle properties in the Shape instances. This means that a shape can only be added to one body. 16e1a47
    • Raycasting API is scratched and rewritten. Replaced World.prototype.raycastAll, .raycastClosest and .raycastAny with .raycast(result, ray). Moved the intersection methods in Ray to their respective Shape. d1feff1
    • Enabled island splitting by default 1aed70b
    • Increased default solver tolerance 1aed70b
    • The "point" argument in Body.prototype.applyForce should now be a vector relative to the Body position, instead of a world point 28494c1

    Fixes

    • Event objects now release references to objects in parameters after emit fe2461b
    • Fix for requirejs via phaser ced0558

    Additions

    • The following options can now be passed via the Shape constructor: material, position, angle, collisionGroup, collisionMask, sensor, collisionResponse 6a20c75 380aaa55d6174a6740de66877aad0f77338444f2
    • Added AABB.prototype.containsPoint 9423e3a
    • Added vec2.getLineSegmentsIntersection and vec2.getLineSegmentsIntersectionFraction a01ee11
    • Added AABB.prototype.overlapsRay
    • Added vec2.reflect ea9b6d5
    • Added TopDownVehicle class 33846a5
    • Added Body.prototype.getVelocityAtPoint 33846a5
    • Added object pools and prefilling 3537a2e 0b2a648
    • Added Body.prototype.applyLocalForce 28494c1
    • The following options can now be passed to Body constructor: allowSleep, collisionResponse, gravityScale, sleepSpeedLimit, sleepTimeLimit, id
    • Added Body.prototype.applyImpulse, .applyImpulseLocal, .vectorToLocalFrame, . vectorToWorldFrame 872ea6c
    • Added vec2.vectorToLocalFrame and vec2.vectorToGlobalFrame 238d120

    Removals

    • Removed GridBroadphase since it is buggy and mostly unused e90c672
    • Removed World.prototype.setGlobalEquationParameters. Use .setGlobalStiffness and .setGlobalRelaxation instead 69d494b3cd53ac2690bda0ddb50890d8566146e9
    • Removed doProfiling and lastStepTime properties from World since it is much easier to use the browser profiling tools nowadays. 4223c88
    • Removed broken method World.prototype.clone c330903
    Source code(tar.gz)
    Source code(zip)
    p2.js(386.96 KB)
    p2.min.js(118.92 KB)
  • v0.6.1(Mar 29, 2015)

    Small release, fixes some bugs and adds basic raycasting + experimental CCD.

    Changes

    • Changed default broadphase algorithm to SAPBroadphase.

    Fixes

    • Fixed bug in endContact event, bodyB had the value of bodyA.
    • Require.js fix for the build files, making it possible to use p2.js on the same page as require.js
    • .idleTime in Body is now initialized correctly
    • All classes now have .constructor set correctly

    Additions

    • Added .collisonResponse flag for Body and Shape.
    • Added methods .raycastClosest, .raycastAll and .raycastAny to World
    • Added method Body.prototype.integrate
    • Added properties .ccdSpeedThreshold and .ccdIterations to Body
    Source code(tar.gz)
    Source code(zip)
    p2.js(361.18 KB)
    p2.min.js(110.97 KB)
    p2.renderer.js(495.28 KB)
    p2.renderer.min.js(212.41 KB)
  • v0.6.0(Jul 9, 2014)

    Breaking changes

    • Renamed property .motionState to .type in class Body.
    • Changed constructor of RevoluteConstraint. Now the local pivots are passed as options instead of direct arguments. See the constraints demo.
    • Removed World.prototype.toJSON and .fromJSON.
    • Removed properties .enableBodySleeping and .enableIslandSleeping from World instances. The enum .sleepMode can be used instead. See the sleep demo.
    • Converted Spring to a base class for the new LinearSpring and RotationalSpring classes. LinearSpring can be used as the old Spring.
    • Utils.ARRAY_TYPE can now be overridden by injecting a global called P2_ARRAY_TYPE. Support for GLMAT_ARRAY_TYPE has been removed.

    Other changes

    • Added flag .enableFrictionReduction to Narrowphase.
    • Added RevoluteConstraint.prototype.setLimits.
    • Added PrismaticConstraint.prototype.setLimits.
    • LockConstraint, DistanceConstraint, and GearConstraint can now be constructed from current body transforms.
    • RevoluteConstraint can now be constructed from the current body transforms and a world point.
    • Material id can now be passed via constructor.
    • ContactMaterial instances now have a property .contactSkinSize.
    • Added method Body.prototype.getAABB.
    • Limits for DistanceConstraint. See the DistanceConstraint demo.
    • Added Body.prototype.overlaps.
    • Added class OverlapKeeper.
    • If substepping is used in World.prototype.step, the substeps are aborted if slower than real time.
    • Added Heightfield/Convex and Heightfield/Circle collision support.
    • Added property .overlapKeeper to World.
    • EventEmitter.prototype.has can now check if any listeners were added to a given topic.
    • Added Utils.defaults.
    Source code(tar.gz)
    Source code(zip)
    p2.js(402.84 KB)
    p2.min.js(147.67 KB)
  • v0.5.0(Apr 5, 2014)

    • Added property .enableIslandSleeping to World.
    • Added property .useFrictionGravityOnZeroGravity to World.
    • Renamed .useWorldGravityForFrictionApproximation in World to .useWorldGravityAsFrictionGravity to keep things more uniform.
    • Sleep improvements.
    • Added property .frictionIterations to GSSolver, and removed .skipFrictionIterations.
    • Upgraded to gl-matrix 2.1.0.
    • Removed QuadTree.
    • Removed mat2.
    • Added Utils.extend.
    • Added methods .setStiffness and .setRelaxation methods to Constraint.
    • Removed properties .stiffness, .relaxation and .useGlobalEquationParameters from GSSolver.
    • Added methods .setGlobalStiffness, .setGlobalRelaxation, .setGlobalEquationParameters to World.
    • Renamed property .eps to .epsilon for Equation.
    • Removed property .useBoundingBoxes from NaiveBroadphase in favor of the new property .boundingVolumeType in Broadphase.
    • Added methods .getMaxForce and .setMaxForce to LockConstraint.
    • Changed property names .bi, .bj, .ni, .ri, .rj to .bodyA, .bodyB, .normalA, .contactPointA, .contactPointB in Equation, ContactEquation and FrictionEquation classes.
    • Removed IslandSolver in favor of the new property World.islandSplit.
    • Changed constructors of the Constraints so they all take an options object as last parameter.
    • Added property .collideConnected to Constraint.
    • Added property .islandSplit to World.
    • Added methods .disableBodyCollision and .enableBodyCollision to World.
    • Added properties .useWorldGravityForFrictionApproximation and .frictionGravity to World.
    • Added Heightfield class.
    • Removed properties .defaultFriction and .defaultRestitution from World, in favor of .defaultContactMaterial.
    • Added property .enabled to Equation.
    • Added property .surfaceVelocity to ContactMaterial.
    • Added property .sensor to Shape.
    • World now emits events 'beginContact', 'endContact' and 'preSolve'.
    • Added property .gravityScale to Body.
    • Renamed class SAP1DBroadphase to SAPBroadphase.
    • Added property .interpolatedPosition to `Body``.
    • Added method .internalStep to World.
    • Added property .applyGravity to World.
    • Renamed method .computeC to .computeInvC in Equation, and made it compute the inverse.
    • Added static method Utils.splice.
    • Added property .world to Body.
    • Added property .fixedRotation to Body.
    • Added class AABB.
    • Added properties .aabb and .aabbNeedsUpdate to Body, as well as a method .updateAABB.
    • Added property .useBoundingBoxes to NaiveBroadphase.
    • Added static method Broadphase.aabbCheck.
    • Added method .computeAABB to Shape.
    • Added static method Broadphase.canCollide.
    • Body now inherits from EventEmitter, and dispatches events 'sleep','sleepy' and 'wakeup'.
    • Added properties .allowSleep, .sleepState, .sleepSpeedLimit, .sleepTimeLimit, .lastTimeSleepy as well as methods .sleep, .wakeUp and .sleepTick to Body.
    • Added enums Body.AWAKE, Body.SLEEPY, Body.SLEEPING.
    • Added property .enableBodySleeping to World.
    • Added options .disableRotationalLock, .lowerLimit, .upperLimit to PrismaticConstraint constructor.
    • Added methods .enableMotor, .disableMotor to PrismaticConstraint as well as properties .motorEnabled, .motorSpeed, .motorEquation.
    Source code(tar.gz)
    Source code(zip)
    p2.js(319.13 KB)
    p2.min.js(101.52 KB)
  • v0.4.0(Jan 22, 2014)

    • Added properties .damping and .angularDamping to Body.
    • Added property .applyDamping to World.
    • Added properties .shapeA and .shapeB to ContactEquation and FrictionEquation.
    • Added property .contactEquation to FrictionEquation.
    • Added property .multiplier to Equation.
    • Added properties .lowerLimitEnabled, .lowerLimit, .upperLimitEnabled, .upperLimit to RevoluteConstraint.
    • Added property .frictionCoefficient to FrictionEquation and Narrowphase. 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 to Narrowphase.planeConvex.
    • Changed name of Narrowphase.capsulePlane to Narrowphase.planeCapsule.
    • Added property .emitImpactEvent to World.
    • Added method .getBodyById to World.
    • Added property .skipFrictionIterations to GSSolver.
    • Changed parameter names for PrismaticConstraint. This breaks backwards compatibility.
    • Added properties .localAxisA, .localAnchorA, .localAnchorB, to PrismaticConstraint.
    Source code(tar.gz)
    Source code(zip)
Owner
Stefan Hedman
Stefan Hedman
A 3rd year University physics project for simulating satellites motion in orbit.

Satellite Simulator VI - Deluxe Edition A university physics project for simulating satellites in orbit. Installation instructions Clone the git repos

Rami Sabbagh 8 Jun 26, 2022
This is an example of Quantum physics congress.

This is an example of Quantum physics congress. This is an imaginary congress in which are shown 2 pages with information about the congress, about activities which will be held there and speakers who will speak about the topic

Sanja Mandic 7 Jun 24, 2022
Open game experiment with vehicles and physics in Three.js

TNTGame Open game experiment with vehicles and physics in Three.js You can try it online here: Crater scene: https://yomboprime.github.io/TNTGame/app?

Juan Jose Luna Espinosa 3 Oct 5, 2022
Reference for How to Write an Open Source JavaScript Library - https://egghead.io/series/how-to-write-an-open-source-javascript-library

Reference for How to Write an Open Source JavaScript Library The purpose of this document is to serve as a reference for: How to Write an Open Source

Sarbbottam Bandyopadhyay 175 Dec 24, 2022
It's an alert library build with JavaScript. You can replace your traditional JavaScript alert, confirm and toast with the library.

asteroid-alert It's an alert library build with JavaScript. You can replace your traditional JavaScript alert, confirm with the library. It has also e

Khan Md Sagar 4 Mar 12, 2021
A JavaScript library built on top of the Faker.JS library. It generates massive amounts of fake data in the browser and node.js.

Blaver - generate massive amounts of fake data in the browser and node.js Blaver is a JavaScript library built on top of the Faker.JS library. It gene

Priyansh 113 Dec 30, 2022
A small javascript DOM manipulation library based on Jquery's syntax. Acts as a small utility library with the most common functions.

Quantdom JS Quantdom is a very small (about 600 bytes when ran through terser & gzipped) dom danipulation library that uuses a Jquery like syntax and

Sean McQuaid 7 Aug 16, 2022
this project is an online library application that enables users to keep track of books in their library by adding to and removing books from a list. Built with JavaScript ES6 syntax, HTML, and CSS

Awesome-Book1 The aim of this project is to restructure the Awesome books app code by using ES6 syntax and organising the workspace using modules. The

Afolabi Akorede 7 Jul 17, 2022
LiveTabs is a Javascript library that allows you to create and manage tabs on the fly. This library gives the ability to your application to act like browser tabs, making dynamic tabs.

LiveTabs Table of content Description Goals Technologies Setup Description LiveTabs is a Javascript library that allows you to create and manage tabs

Hossein Khalili 3 May 3, 2022
This package will help parse OData strings (only the Microsoft Dataverse subset). It can be used as a validator, or you can build some javascript library which consumes the output of this library.

@albanian-xrm/dataverse-odata This package will help parse OData strings (only the Microsoft Dataverse subset). It can be used as a validator, or you

AlbanianXrm 3 Oct 22, 2022
Ping.js is a small and simple Javascript library for the browser to "ping" response times to web servers in Javascript

Ping.js Ping.js is a small and simple Javascript library for the browser to "ping" response times to web servers in Javascript! This is useful for whe

Alfred Gutierrez 353 Dec 27, 2022
Simple Library implemented using HTML, CSS and JavaScript. This is a simple implementation of JavaScript Modules of ES6.

Awesome-books A single page project with the porpuse of storing books' titles and authors. Built With CSS, HTML & Javascript. How to run in your local

Saadat Ali 7 Feb 21, 2022
A Powerful and Elegant "alert" library for JavaScript that replaces that boring alert style of Javascript.

A Powerful , Elegant and fully customizable "alert" library using JavaScript that replaces that boring style of alert. Installation Place the below sc

Cosmogic 11 Aug 10, 2021
Device.js is a JavaScript library to detect device, viewport, and browser information using plain JavaScript.

Device.js Device.js is a JavaScript library to detect device, viewport, and browser information using plain JavaScript. Compatibility Works with all m

Emanuel R. Vásquez 5 Dec 16, 2022
This is my to-do list website built with html, css and JavaScript. In this project I used Webpack to bundle JavaScript and ES6 modules to write modular JavaScript.

To-Do-List App This is my to-do list website built with html, css and JavaScript. In this project I used Webpack to bundle JavaScript and ES6 modules

Samuel Mwape 18 Sep 20, 2022
AweSome Book App displays the book details entered by user and saves the information in Local storage. User can add and remove a book title/author to the library and from the library.

Awesome Book App with ES6 Used npm init -y command to create package.json file. Created the entry point for the JavaScript code called index.js Create

Krishna Prasad Acharya 8 Aug 15, 2022
A JavaScript library to create html elements with js easily

applecake is a javascript library for making HTML elements with javascript really easy . Why applecake ? Really easy to use It is not heavy It has a s

null 4 Jul 21, 2021
A drum synthesis library in JavaScript with Elementary

drumsynth A small drum synthesis library for Elementary. Installation $ npm install @nick-thompson/drumsynth Usage const core = require('elementary-co

Nick Thompson 75 Jan 1, 2023
A JavaScript Library for things I use often, as well as some helper functions

Elements A JavaScript Library for things I use often, as well as some helper functions. Full documentation below. Inspired by Habitat, another library

Magnogen 3 Apr 21, 2022