Line-Circle Collision Detection

1.1.3 · maintenance · verified Wed Apr 22

The `line-circle-collision` package provides a focused utility for performing 2D collision tests between a line segment and a circle. It returns a boolean indicating whether an intersection occurred and can optionally store the nearest collision point. The current stable version is 1.1.3, last published in 2014. Given its stability and specific use case, it operates under a maintenance cadence rather than active feature development. This package differentiates itself by offering a simple, low-level geometric test without the overhead of a full physics engine, making it suitable for projects requiring precise collision detection for these specific shapes. It's often used in conjunction with other basic geometric utilities like `point-in-triangle` or `point-circle-collision` for building more complex collision systems.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use the `collide` function to check for an intersection between a line segment and a circle, including how to retrieve the nearest collision point if a hit occurs.

const collide = require('line-circle-collision');

// Define the circle (center X, center Y) and its radius
const circleCenter = [50, 50];
const radius = 25;

// Define the line segment by its two endpoints (A and B)
const linePointA = [20, 30];
const linePointB = [80, 70];

// Optional: a vector to store the nearest collision point
const nearestPoint = [0, 0]; 

// Perform the collision test
const hit = collide(linePointA, linePointB, circleCenter, radius, nearestPoint);

if (hit) {
  console.log(`Collision detected!`);
  console.log(`Nearest collision point: [${nearestPoint[0]}, ${nearestPoint[1]}]`);
} else {
  console.log('No collision.');
}

// Example of no collision
const noHitLineA = [0,0];
const noHitLineB = [10,10];
const noHit = collide(noHitLineA, noHitLineB, circleCenter, radius);
console.log(`No collision example: ${noHit}`);

view raw JSON →