p2.js Documentation

repository·master·Indexed 25 days ago

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

A JavaScript 2D rigid body physics engine (version 0.7.1) supporting collision detection, contacts, friction, restitution, motors, springs, and advanced constraints. It provides a variety of shape types including Circle, Plane, Box, Convex, Particle, Line, Capsule, Heightfield, and Ray, making it suitable for games and interactive simulations.

Tokens
6.2K
Snippets
11
Records
34
Agent score
82%

What's inside p2.js

  1. Install p2.js in the browser

    master

    To use p2.js in a web browser, download p2.js or p2.min.js and include it in your HTML via a <script> tag.

    By default, the engine uses Float32Array for performance. If you prefer to use standard JavaScript Array objects, define the global P2_ARRAY_TYPE variable before loading the library.

  2. Interact with bodies using postStep listeners

    master

    When interacting with bodies (e.g., applying forces), do so after each internal step to ensure stability. Attach a postStep listener to the world object.

    Note: Use body.position for physics calculations/interactions. Use body.interpolatedPosition only for rendering purposes.

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

    master

    Create a World instance to manage bodies, constraints, and the physics simulation. You can configure the gravity, the solver, and the broadphase algorithm during initialization.

    Options:

    • solver: The solver used to satisfy constraints and contacts. Defaults to GSSolver.
    • gravity: An array [x, y] representing gravity. Defaults to y=-9.78.
    • broadphase: The broadphase algorithm. Defaults to SAPBroadphase.
    • islandSplit: Boolean to enable/disable island splitting for performance/precision. Defaults to true.
    var World = require('./src/world/World');
    var SAPBroadphase = require('./src/collision/SAPBroadphase');
    
    var world = new World({
        gravity: [0, -10],
        broadphase: new SAPBroadphase()
    });
  4. Configure collision filtering with collisionGroup and collisionMask

    master

    You can control which shapes collide using bitwise masks.

    • collisionGroup: A bit mask representing the group this shape belongs to.
    • collisionMask: A bit mask representing the groups this shape is allowed to collide with.

    A collision occurs only if (shapeA.collisionGroup & shapeB.collisionMask) != 0 AND (shapeB.collisionGroup & shapeA.collisionMask) != 0.

  5. Set up a basic physics scene with p2.js

    master

    To create a physics simulation, you need to instantiate a p2.World, create p2.Body objects, add shapes (like p2.Circle or p2.Plane) to those bodies, and add the bodies to the world. To animate the simulation, call world.step() within an animation loop using a fixed time step.

    // 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);
  6. Configure Shape options

    master

    When instantiating a shape (via a subclass of Shape), you can pass an options object to configure its initial state. Note that Shape is a base class and should not be used directly.

    Available Options:

    • angle (number): Body-local angle. Defaults to 0.
    • collisionGroup (number): Bit mask for the collision group. Defaults to 1.
    • collisionMask (number): Bit mask for the collision mask. Defaults to 1.
    • collisionResponse (boolean): If true, the shape produces contact forces. If false, the shape will move through other shapes but still trigger contact events. Defaults to true.
    • material (Material): Material properties for collisions. Defaults to null (uses world defaults).
    • position (array): Body-local position (e.g., [x, y]).
    • sensor (boolean): If true, the shape becomes a sensor. Sensors do not generate contact forces but still report contact events. Defaults to false.
    • type (number): The shape type (see Shape static constants).
  7. Reference supported collision pairs

    master

    The following table lists the supported collision pairs for various shape types in p2.js:

    ShapeCirclePlaneBoxConvexParticleLineCapsuleHeightfieldRay
    CircleYes--------
    PlaneYes--------
    BoxYesYesYes------
    ConvexYesYesYesYes-----
    ParticleYesYesYesYes-----
    LineYesYes(todo)(todo)-----
    CapsuleYesYesYesYesYes(todo)Yes--
    HeightfieldYes-YesYes(todo)(todo)(todo)--
    RayYesYesYesYes-YesYesYes-
  8. Access p2.js core modules

    master
    The p2 object is the main entry point for the physics engine. It provides access to all core classes including shapes, bodies, constraints, solvers, and mathematical utilities. You can use this object to instantiate the physics world and its constituent parts.
  9. Configure Constraint Stiffness, Relaxation, and Bias

    master

    You can adjust the physical properties of a constraint using the following methods. These methods iterate through the internal equations of the constraint to apply the settings.

    • setStiffness(stiffness): Sets the stiffness for the constraint equations. Sets needsUpdate to true for each equation.
    • setRelaxation(relaxation): Sets the relaxation for the constraint equations. Sets needsUpdate to true for each equation.
    • setMaxBias(maxBias): Sets the maximum bias for the constraint equations.