Custom Collision Detection
Collision detection algorithms determine which droppable area a draggable item should interact with during a drag operation. dnd-kit provides several built-in algorithms and allows you to create custom ones for specialized use cases.Understanding Collision Detection
A collision detector is a function that receives information about the current drag operation and a droppable target, and returns a collision result with a value indicating the strength of the collision.Built-in Algorithms
dnd-kit includes several collision detection algorithms:closestCenter
Detects the droppable whose center is closest to the drag source. This is ideal for general-purpose drag and drop.packages/collision/src/algorithms/closestCenter.ts
Point.distance(droppable.shape.center, shape?.current.center ?? position.current) and returns 1 / distance as the collision value.
pointerIntersection
High-precision algorithm that only detects collisions when the pointer is directly over a droppable element.packages/collision/src/algorithms/pointerIntersection.ts
droppable.shape.containsPoint(pointerCoordinates) and has high priority (CollisionPriority.High).
directionBiased
Detects collisions based on movement direction, perfect for sortable lists where you only want to detect items in the direction you’re moving.packages/collision/src/algorithms/directionBiased.ts
Custom Collision Detection Examples
Example 1: Zone-Based Collision Detection
Create a collision detector that prioritizes specific zones on your canvas:Example 2: Threshold-Based Collision
Only detect collisions when the draggable overlaps a droppable by a certain percentage:Example 3: Combining Multiple Algorithms
Chain multiple collision detection strategies with fallback logic:Example 4: Grid-Snapping Collision Detection
Detect the nearest grid cell for precise placement:Best Practices
-
Return null for non-collisions: Always return
nullwhen there’s no collision instead of a result with a value of 0. -
Use appropriate priorities: Set
CollisionPriority.Highfor precise collisions (like pointer intersection) andCollisionPriority.Normalfor proximity-based detection. -
Normalize collision values: Keep collision values in a reasonable range. The built-in algorithms use
1 / distancewhich provides good resolution. -
Guard against null shapes: Always check if
droppable.shapeexists before accessing its properties. - Consider performance: Collision detection runs frequently during dragging. Keep calculations lightweight.
Collision Types
The library defines several collision types that affect how collisions are processed:CollisionType.Collision- Standard collision detectionCollisionType.PointerIntersection- High-precision pointer-based collisionCollisionType.ShapeIntersection- Shape-based overlap detection