Matter.js

repository·master·Indexed 12 days ago

https://github.com/liabru/matter-js

A 2D rigid body physics engine for the web, version 0.20.0. It supports compound bodies, concave/convex hulls, constraints, and a plugin system. Key features include collision filtering via categories and masks, broadphase collision detection, and a comprehensive Body API for manipulating mass, density, inertia, and velocity.

Tokens
12.2K
Snippets
40
Records
54
Agent score
97%

What's inside Matter.js

  1. Install matter-js

    master

    You can install matter-js using npm or Yarn, or by including the script directly in your HTML.

    Using npm

    npm install matter-js

    Using Yarn

    yarn add matter-js

    Using a script tag

    Download a stable release and include it in your web page:

    <script src="matter.js" type="text/javascript"></script>
  2. Configure collision filtering for a body

    master

    You can control which bodies collide using the collisionFilter object. It uses two main methods:

    1. Group-based filtering: If two bodies have the same non-zero collisionFilter.group value, they will always collide if the value is positive, and never collide if the value is negative.
    2. Category and Mask filtering: If groups are different or zero, the engine uses bitwise logic. A body A collides with body B only if (categoryA & maskB) !== 0 AND (categoryB & maskA) !== 0.

    category should be a power of two (e.g., 0x0001, 0x0002) representing one of 32 possible categories. mask is a bitmask of all categories the body is allowed to collide with.

  3. How Matter.Runner manages engine updates

    master

    The Matter.Runner uses a timeBuffer to accumulate elapsed time between browser frames. It then attempts to run as many Engine.update calls as necessary to catch up to the elapsed time, using the fixed delta specified in the runner configuration.

    To prevent the simulation from consuming too much CPU and blocking the browser UI, the runner respects two performance budgets:

    1. maxFrameTime: Limits the total execution time of the runner's tick.
    2. maxUpdates: Limits the total number of engine updates per frame.

    If these budgets are exceeded, the runner will defer remaining updates to the next frame by storing the remaining time in the timeBuffer.

  4. How to create a Matter.js plugin

    master

    To be considered a valid plugin by the Matter.js Plugin system, an object must implement the following properties:

    • name: A unique string identifier for the plugin.
    • version: A semver-compatible version string (e.g., '1.0.0').
    • install: A function that is called when the plugin is installed on a module. This function receives the target module as its argument.

    Additionally, you can optionally specify a for property to restrict the plugin to specific modules or versions. The format for for is 'module-name' or 'module-name@version'. If for is not specified, the plugin is assumed to be applicable to any module.

    const myPlugin = {
        name: 'my-plugin',
        version: '1.0.0',
        install: function(module) {
            // Extend the module here
            console.log('Installing my-plugin on', module.name);
        }
    };
  5. Use Matter.Vector for 2D math operations

    master

    Matter.Vector is a utility module for creating and manipulating 2D vectors. A vector in Matter.js is a plain JavaScript object with the shape { x: number, y: number }. This module provides essential methods for physics-related calculations such as addition, subtraction, rotation, and magnitude.

    Most methods allow for an optional output parameter. If provided, the result is written into that object instead of creating a new one, which helps reduce garbage collection overhead in high-frequency physics loops.

    // Example of creating and adding vectors
    const v1 = Matter.Vector.create(10, 20);
    const v2 = Matter.Vector.create(5, 5);
    
    // Returns a new vector { x: 15, y: 25 }
    const result = Matter.Vector.add(v1, v2);
    
    // Using an output object to avoid allocation
    const output = { x: 0, y: 0 };
    Matter.Vector.add(v1, v2, output);
  6. Use Matter.Runner to create a game loop

    master

    The Matter.Runner module provides an optional utility for running a Matter.Engine inside a browser environment. It synchronizes engine updates with the browser's frame rate, favoring a smooth user experience over perfect timekeeping.

    To use it, create a runner instance with Runner.create(options) and then start it with Runner.run(runner, engine). To stop the loop entirely, use Runner.stop(runner). To temporarily pause updates without stopping the loop, toggle the runner.enabled property.

    var runner = Matter.Runner.create();
    var engine = Matter.Engine.create();
    
    Matter.Runner.run(runner, engine);
  7. Performance considerations with Webpack and Vue.js

    master

    When integrating matter-js with certain bundlers or frameworks, default configurations may impact real-time physics performance:

    • Webpack: The default sourcemap configuration can significantly impact performance. Refer to this issue for solutions.
    • Vue.js: Vue's watchers can have a large impact on performance. Refer to this issue comment for a solution.
  8. Configure Matter.Runner options

    master

    When calling Runner.create(options), you can pass a configuration object to tune the runner's behavior.

    Key options include:

    • delta: The fixed timestep size used for Engine.update calls in milliseconds (default: 1000 / 60). Smaller values increase simulation quality but cost more performance.
    • enabled: A boolean to enable or disable tick calls (default: true).
    • maxFrameTime: A performance budget in milliseconds that limits execution time per browser frame (default: 1000 / 30).
    • maxUpdates: An optional limit for the maximum number of engine updates allowed per frame (default: null).
    • frameDeltaSmoothing: Enables averaging to smooth frame rate measurements (default: true).
    • frameDeltaSnapping: Rounds measured browser frame delta to the nearest 1 Hz (default: true).
    var runner = Matter.Runner.create({
        delta: 1000 / 120,
        maxFrameTime: 1000 / 60,
        frameDeltaSmoothing: true
    });
  9. Configure Webpack for Matter.js Demos

    master

    The webpack.demo.config.js file provides a configuration template for building the Matter.js demo application. It supports different modes based on environment variables and flags.

    Environment Variables and Flags

    • ANALYZE: Set this environment variable to true to trigger the BundleAnalyzerPlugin, which helps visualize the size of the generated bundles.
    • WEBPACK_DEV_SERVER: Setting this environment variable enables devServer mode, which changes the output path, public path, and disables source maps/minimization for faster development.

    Key Configuration Behaviors

    • Library Output: The bundle is exported as a UMD library named MatterDemo.
    • Minification: Minification is automatically enabled unless WEBPACK_DEV_SERVER is active.
    • Module Aliasing: The configuration provides aliases to facilitate development:
      • matter-js: Points to the source module entry point.
      • MatterDev: Points to the source module entry point.
      • MatterBuild: Points to the build path in production or the source path in development.
    • Global Constants: The build injects __MATTER_VERSION__ and __MATTER_IS_DEV__ (boolean) via DefinePlugin.
    # To run with bundle analysis
    ANALYZE=true npx webpack --config webpack.demo.config.js
    
    # To run with dev server
    WEBPACK_DEV_SERVER=true npx webpack serve --config webpack.demo.config.js
  10. Rotate a vector about a specific point

    master

    To rotate a vector around a pivot point rather than the origin (0, 0), use Matter.Vector.rotateAbout. This is useful for orbital mechanics or rotating objects around their center of mass.

    Matter.Vector.rotateAbout(vector, angle, point, [output])

    • vector: The vector to rotate.
    • angle: The rotation angle in radians.
    • point: The pivot point { x, y }.
    • output (optional): An existing vector object to store the result.
    const center = { x: 100, y: 100 };
    const pos = { x: 110, y: 100 };
    const angle = Math.PI; // 180 degrees
    
    // Rotates 'pos' around 'center'
    const newPos = Matter.Vector.rotateAbout(pos, angle, center);
    // newPos will be { x: 90, y: 100 }