{"name":"detect-collisions","version":"9.23.2","keywords":["javascript","typescript","library","computational-geometry","alghoritm","computational-geometry-alghoritm","collisions","collision-checking","concave","rotation","angle","separating-axis-theorem","bounding-volume-hierarchy","Circle","Polygon","Box","Ellipse","Line","Point"],"author":{"name":"Jacek Pietal"},"license":"MIT","_id":"detect-collisions@9.23.2","homepage":"https://prozi.github.io/detect-collisions/","bugs":{"url":"https://github.com/Prozi/detect-collisions/issues"},"dist":{"shasum":"602bdb24f6b5b85a29afe16fb1b3f509fcf3d71c","tarball":"http://registry-npm.ywwl.com/detect-collisions/download/detect-collisions-9.23.2.tgz","fileCount":33,"integrity":"sha512-9782cdMg6D/NtpdxD59DFFbP1/F3bxdeZ2npg11EML8QiR7XR9eHvqOiLOuA0oi+ggfSkjCDAqZ3n9MbV5gVxA==","signatures":[{"sig":"MEUCIQCB3B9lqKX3wqdIkrxf4Jr+24NG6Z3g7lDtMdYheEVVwAIgCH1l5kT76S1YkuNHnVjBZ2sSaipc3a2RDVbbyTsk1SM=","keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA"}],"unpackedSize":118335,"size":29808,"noattachment":false,"key":"/detect-collisions/-/detect-collisions-9.23.2.tgz"},"main":"dist/index.js","types":"dist/index.d.ts","gitHead":"dc5e0c2128dd9c3ebe658027ed1df782a45a2f69","scripts":{"dev":"webpack serve --port 3000","demo":"npm run build:demo && npm start","docs":"npm run build:docs && chef-express docs --debug --port 3000","lint":"eslint src --fix","test":"jest --silent --verbose --forceExit","amend":"npm run precommit;git commit -a --am --no-edit","build":"tsc","start":"chef-express dist/demo --debug --port 3000","prebuild":"rm -rf dist && npm run copy-npm-modules","benchmark":"npm run benchmark-insertion && npm run benchmark-stress","postbuild":"npm run test && npm run build:docs && npm run build:demo && ./clean-dist.sh && npm run benchmark","precommit":"npm run lint && npm run build","build:demo":"webpack","build:docs":"typedoc --customCss typedoc.css","copy-rbush":"cp node_modules/rbush/index.js src/external/rbush.js","prebuild:docs":"rm -rf docs","postbuild:demo":"cp -r dist/demo docs","postbuild:docs":"npm run docs-from-master || echo ok","benchmark-stress":"node -e 'import(\"./dist/benchmarks/index.js\").then(({ stressBenchmark }) => stressBenchmark());'","copy-npm-modules":"npm run copy-rbush && npm run copy-quickselect && npm run use-latest-quickselect","copy-quickselect":"cp node_modules/quickselect/index.js src/external/quickselect.js","docs-from-master":"npm run docs-from-master-macos || npm run docs-from-master-linux","benchmark-insertion":"node -e 'import(\"./dist/benchmarks/index.js\").then(({ insertionBenchmark }) => insertionBenchmark());'","docs-from-master-linux":"find docs -type f -name '*.html' -exec sed -i -r 's_/blob/[^/]+/_/blob/master/_g' {} +","docs-from-master-macos":"find docs -type f -name '*.html' -exec sed -i '' -r 's_/blob/[^/]+/_/blob/master/_g' {} +","use-latest-quickselect":"npm run use-latest-quickselect-macos || npm run use-latest-quickselect-linux","use-latest-quickselect-linux":"sed -i -r \"s_'quickselect'_'./quickselect'_g\" src/external/rbush.js","use-latest-quickselect-macos":"sed -i '' -e \"s_'quickselect'_'./quickselect'_g\" src/external/rbush.js"},"_npmUser":{"name":"pietal.dev","email":"prozi85+pietal.dev@gmail.com"},"repository":{"url":"git://github.com/Prozi/detect-collisions.git","type":"git"},"_npmVersion":"10.9.0","description":"Points, Lines, Boxes, Polygons (also hollow), Ellipses, Circles. RayCasting, offsets, rotation, scaling, bounding box padding, flags for static and ghost/trigger bodies","directories":{},"resolutions":{"json5":"^2.2.2","canvas":"^2.11.2","semver":"^7.5.3","terser":"^5.14.2","express":"^4.19.2","minimist":"^1.2.6","escodegen":"^2.1.0","@types/node":"^22.4.1"},"_nodeVersion":"20.18.0","dependencies":{"sat":"^0.9.0","@types/sat":"^0.0.35","poly-decomp-es":"^0.4.2"},"_hasShrinkwrap":false,"devDependencies":{"jest":"^29.7.0","husky":"^9.1.6","rbush":"^4.0.1","eslint":"^9.13.0","ts-jest":"^29.2.5","typedoc":"^0.26.10","webpack":"^5.96.0","tinybench":"^3.0.3","ts-loader":"^9.5.1","typescript":"^5","@types/node":"^22.8.6","quickselect":"^3.0.0","random-seed":"^0.3.0","webpack-cli":"^5.1.4","@types/rbush":"^4.0.0","chef-express":"^2.4.2","eslint-plugin-json":"^4.0.1","webpack-dev-server":"^5.1.0","html-webpack-plugin":"^5.6.3","@stylistic/eslint-plugin":"^2.10.0"},"_npmOperationalInternal":{"tmp":"tmp/detect-collisions_9.23.2_1730438056140_0.19773760875353297","host":"s3://npm-registry-packages"},"readme":"# Detect-Collisions\n\n[<img src=\"https://img.shields.io/npm/v/detect-collisions?style=for-the-badge&color=success\" alt=\"npm version\" />](https://www.npmjs.com/package/detect-collisions?activeTab=versions)\n[<img src=\"https://img.shields.io/npm/dw/detect-collisions.svg?style=for-the-badge&color=success\" alt=\"npm downloads per week\" />](https://www.npmjs.com/package/detect-collisions)\n[<img src=\"https://img.shields.io/circleci/build/github/Prozi/detect-collisions/master?style=for-the-badge\" alt=\"build status\" />](https://app.circleci.com/pipelines/github/Prozi/detect-collisions)\n\n## Introduction\n\nDetect-Collisions 💫 is a lightning-fast ⚡️ TypeScript library built to detect collisions between diverse shapes like Points, Lines, Boxes, Polygons (including concave), Ellipses, and Circles. Utilizing Bounding Volume Hierarchy (BVH) and the Separating Axis Theorem (SAT), it offers rapid and accurate collision detection. The library supports RayCasting, offsets, rotation, scaling, and optimizations for: bounding box, flags for non-moving and ghost/trigger bodies and collision groups filtering - making it an ideal choice for high-speed applications in gaming and simulations.\n\n## Demos\n\n- [Tank](https://prozi.github.io/detect-collisions/demo/)\n- [Stress Test](https://prozi.github.io/detect-collisions/demo/?stress)\n- [Stackblitz](https://stackblitz.com/edit/detect-collisions)\n- [CodePan](https://code.pietal.dev/#/boilerplate/detect-collisions?pans=html,console)\n\n## Installation\n\n```bash\nnpm i detect-collisions --save\n```\n\n## API Documentation\n\nFor detailed documentation on the library's API, refer to the following link:\n\n[Detect-Collisions API Documentation](https://prozi.github.io/detect-collisions/)\n\n## Usage\n\n### Step 1: Initialize Collision System\n\nInitialize a unique collision system using Detect-Collisions:\n\n```ts\nconst { System } = require(\"detect-collisions\");\nconst system = new System();\n```\n\n### Step 2: Understand Body Attributes\n\nBodies possess various properties:\n\n- **Position**: Use `setPosition(x: number, y: number)` for teleport and `move(speed: number)` for moving forward in direction of its angle.\n- **Scale**: Use `setScale(x: number, y: number)` for setting and `scale: Vector` for getting scale\n- **Rotation**: Use `setAngle(radians: number)` for setting and `angle: number` for getting and `deg2rad(degrees: number)` to convert to radians.\n- **Offset**: Use `setOffset(offset: Vector)` for setting and `offset: Vector` for getting offset from the body center.\n- **AABB Bounding Box**: Use `aabb: BBox` for inserted or `getAABBAsBBox(): BBox` for non inserted bodies to get the bounding box.\n- **Padding**: Use `padding: number` and set to nonzero value to reduce costly reinserts on attributes' change.\n- **Collision Filtering**: Use `group: number` for collision filtering, with a range within 0x0 ~ 0x7fffffff.\n- **Body Options**: [Read more in BodyOptions documentation](https://prozi.github.io/detect-collisions/interfaces/BodyOptions.html)\n\n### Step 3: Create and Manage Bodies\n\nCreate bodies of various types and manage them:\n\n```ts\nconst {\n  Box,\n  Circle,\n  Ellipse,\n  Line,\n  Point,\n  Polygon,\n} = require(\"detect-collisions\");\n\n// Example: Create and insert box1 body\nconst box1 = system.createBox(position, width, height, options);\n// Example: Create box2 body\nconst box2 = new Box(position, width, height, options);\n// Example: Insert box2 body\nsystem.insert(box2);\n```\n\n### Step 4: Manipulate Bodies\n\nManipulate body attributes and update the collision system:\n\n```ts\n// if omitted updateNow is true\nconst updateNow = false;\n// this should be time scaled, 1 for example\nconst speed = 1;\n\n// teleport\nbox.setPosition(x, y, updateNow);\nbox.setScale(scaleX, scaleY, updateNow);\nbox.setAngle(angle, updateNow);\nbox.move(speed, updateNow);\nbox.setOffset({ x, y }, updateNow);\nconsole.log(box.dirty); // true\n\nbox.updateBody(); // Update the body once, when all manipulations are done\nconsole.log(box.dirty); // false\n\nbox.group = group; // Immediate effect, no body/system update needed\nconsole.log(box.dirty); // false\n```\n\n### Step 5: Collision Detection and Resolution\n\nDetect collisions and respond accordingly:\n\n```ts\nif (system.checkAll(callback)) {\n  // Do something yourself\n}\n\nif (system.checkOne(body, callback)) {\n  // Do something yourself\n}\n\n// Or separate bodies based on isStatic/isTrigger\nsystem.separate();\n```\n\n### Step 6: Cleaning Up\n\nRemove bodies when they're no longer needed:\n\n```ts\nsystem.remove(body);\n```\n\nAnd that's it! You're now ready to utilize the Detect-Collisions library in your project.\n\n## Visual Debugging with Rendering\n\nTo facilitate debugging, Detect-Collisions allows you to visually represent the collision bodies. By invoking the `draw()` method and supplying a 2D context of a `<canvas>` element, you can draw all the bodies within a collision system. You can also opt to draw individual bodies.\n\n```ts\nconst canvas = document.createElement(\"canvas\");\nconst context = canvas.getContext(\"2d\");\n\ncontext.strokeStyle = \"#FFFFFF\";\ncontext.beginPath();\n// draw specific body\nbody.draw(context);\n// draw whole system\nsystem.draw(context);\ncontext.stroke();\n```\n\nTo assess the [Bounding Volume Hierarchy](https://en.wikipedia.org/wiki/Bounding_volume_hierarchy), you can draw the BVH.\n\n```ts\ncontext.strokeStyle = \"#FFFFFF\";\ncontext.beginPath();\n// draw specific body bounding box\nbody.drawBVH(context);\n// draw bounding volume hierarchy of the system\nsystem.drawBVH(context);\ncontext.stroke();\n```\n\n## Raycasting\n\nDetect-Collisions provides the functionality to gather raycast data. Here's how:\n\n```ts\nconst start = { x: 0, y: 0 };\nconst end = { x: 0, y: -10 };\nconst hit = system.raycast(start, end, (body, ray) => {\n  // if you don't want the body to be hit by raycast return false\n  return true;\n});\n\nif (hit) {\n  const { point, body } = hit;\n\n  console.log({ point, body });\n}\n```\n\nIn this example, `point` is a `Vector` with the coordinates of the nearest intersection, and `body` is a reference to the closest body.\n\n## Usage in Browsers\n\nJust do what I did here, import from proper cdn as module, and v'oila:\n\n<https://code.pietal.dev/#/boilerplate/detect-collisions?pans=html,console>\n\n## Contributing to the Project\n\nWe welcome contributions! Feel free to open a merge request. When doing so, please adhere to the following code style guidelines:\n\n- Execute the `npm run precommit` script prior to submitting your merge request\n- Follow the [conventional commits](https://www.conventionalcommits.org/en/v1.0.0/#summary) standard\n- Refrain from using the `any` type\n\n## Additional Considerations\n\n### Why not use a physics engine?\n\nWhile physics engines like [Matter-js](https://github.com/liabru/matter-js) or [Planck.js](https://github.com/shakiba/planck.js) are recommended for projects that need comprehensive physics simulation, not all projects require such complexity. In fact, using a physics engine solely for collision detection can lead to unnecessary overhead and complications due to built-in assumptions (gravity, velocity, friction, etc.). Detect-Collisions is purpose-built for efficient and robust collision detection, making it an excellent choice for projects that primarily require this functionality. It can also serve as the foundation for a custom physics engine.\n\n## Benchmark\n\nThis will provide you with the results of both the insertion test benchmark and a headless [Stress Demo](https://prozi.github.io/detect-collisions/demo/?stress) benchmark, featuring moving bodies, with increasing amounts in each step.\n\n```bash\ngit clone https://github.com/Prozi/detect-collisions.git\ncd detect-collisions\nnpm i && npm run build # will build & run tests & run benchmarks\n```\n\n## License\n\nMIT\n\n## You can buy me a coffee\n\n<https://paypal.me/jacekpietal>\n","publish_time":1730438056332,"maintainers":[{"name":"pietal.dev","email":"prozi85+pietal.dev@gmail.com"},{"name":"jacekpietal","email":"prozi85@gmail.com"}],"_cnpm_publish_time":1730438056332,"dist-tags":{"latest":"10.10.2025"}}