August 14th, 2024

Sort, sweep, and prune: Collision detection algorithms

The sweep-and-prune algorithm enhances collision detection in video games by reducing checks through sorting, achieving an average time complexity of O(n + m), improving performance over naive methods.

Read original articleLink Icon
AppreciationCuriosityEnjoyment
Sort, sweep, and prune: Collision detection algorithms

The article discusses the sweep-and-prune algorithm for collision detection in video games, emphasizing its efficiency compared to naive methods. Collision detection is crucial for game mechanics, such as preventing characters from passing through each other or simulating interactions like bouncing. The naive approach, which checks every possible pair of objects for collisions, has a time complexity of O(n²), leading to performance issues as the number of objects increases. The article proposes improvements by leveraging sorting and the transitive property of inequalities to reduce unnecessary checks. By sorting objects based on their minimum x-coordinates, the algorithm can skip pairs that are guaranteed not to collide, significantly enhancing performance. The modified algorithm combines sorting with an early exit strategy in the nested loop, resulting in an average time complexity of O(n + m), where m is the number of overlapping pairs. This approach is particularly effective in scenarios where objects are evenly distributed, making it suitable for many types of games.

- The sweep-and-prune algorithm is an efficient method for collision detection in games.

- Naive collision detection has a time complexity of O(n²), which becomes impractical with many objects.

- Sorting objects by their minimum x-coordinates allows for skipping unnecessary collision checks.

- The modified algorithm achieves an average time complexity of O(n + m), improving performance significantly.

- This method is particularly effective for games with evenly distributed objects.

AI: What people are saying
The comments on the article about the sweep-and-prune algorithm for collision detection reveal several key insights and themes from the community.
  • Many commenters appreciate the article's clarity and accessibility, noting its importance for understanding complex systems in game development.
  • There is a discussion about the efficiency of different sorting algorithms, with some suggesting that insertion sort may outperform traditional fast algorithms due to the nature of object movement in games.
  • Several users mention alternative methods for collision detection, such as spatial hashing and quad-trees, indicating a broader interest in various approaches.
  • Commenters express curiosity about the performance comparison between the sweep-and-prune algorithm and other techniques like space partitioning.
  • Interactive illustrations in the article are praised for enhancing understanding without overshadowing the content.
Link Icon 22 comments
By @jonnycat - 6 months
One interesting note on this approach is that the author suggests using a "fast" sorting algorithm like mergesort/quicksort as the sorting algorithm for best performance. But in practice, you may get better performance from a "worse" sorting algorithm: insertion sort.

The reason is that objects in collision detection systems tend to move relatively small steps between frames, meaning you can keep lists from the previous frame that are already mostly sorted. For sorting these mostly sorted lists, insertion sort tends towards O(n) while Quicksort tends towards O(n^2)!

By @AndrewKemendo - 6 months
This was really well put together.

What’s funny is that I’ve been doing some form of gamedev since late 90s and most of this is abstracted by engines at this point, but this is essential to understanding how complex system simulations work.

Thanks to the author for making a very accessible article

By @bob1029 - 6 months
I've always enjoyed this document regarding continuous collision detection:

https://github.com/bepu/bepuphysics2/blob/master/Documentati...

The library itself is amazing in terms of performance. It is a bit challenging to integrate with though due to the amount of optimization involved.

By @JKCalhoun - 6 months
> This naive algorithm runs in O(n2) time in Big O terms.

Is this true? The naive algorithm's outer loop (i) counts n - 1, while the inner loop (j) begins at i + 1 (so counts progressively less than n - 1).

Not a CS major, is this roughly equivalent (for large values of n) to O(n2) or is it, as it appears, something less?

By @marginalia_nu - 6 months
I enjoyed the use of illustration. Seems like an appropriate usage.

Sometimes I feel like these articles with interactive illustrations are more like an excuse to put together a bunch of cool demos, like there's a lot of fluff with not much substance (a bit like a TED talk), but this one didn't let the illustrations take over.

By @fuzzythinker - 6 months
By @nox101 - 6 months
A long time ago I did something similar but rather than sorting I just kept index lists for each direction and the objects sorted themselves. Meaning like there are 4 lists `objectIndicesSortedByLeftEdge/RightEdge/TopEdge/BottomEdge` If an object moves horizontally then it updates its own indices in the leftEdge and rightEdge arrays. This is because as it moves it likely only has to swap 1 or 2 indices at most to move itself.
By @rendaw - 6 months
I hadn't seen this before, but isn't it similar to using something like a quad-tree to reduce the number of potential colliders?
By @denvaar - 6 months
Got distracted (in a good way) by this website. It's fun and inspiring.
By @RaftPeople - 6 months
> I won’t cover other approaches, such as space partitioning or spatial tree subdivision

I'm curious about this comment, anyone know if the algorithm in the article is generally faster than space partitioning/spatial tree subdivision?

A long time ago I used a spatial tree type of approach which seemed naively to be a pretty good approach, but I never investigated or compared algorithms other people were using (this was 80's, pre-internet).

By @whatever1 - 6 months
I was curious if any linear programming methods have been proposed for the problem since you just need to see if a point is inside a polyhedron or if two polyhedra intersect. There are.https://users.encs.concordia.ca/~akgunduz/CollisionDetection...
By @wood_spirit - 6 months
A tangent, but HNers interested in an article on collision detection might know: are there any similar articles that show how to compute the intersection of two capsules (as in the space that that a sphere moving in a straight line in a time step occupies) in 3D? My own hobby 3D game got stuck on that hurdle and I couldn’t find any examples anywhere :(
By @bambax - 6 months
Excellent article. Sorting the list is a really simple and neat idea, without the need for clustering or a special data structure.
By @MrLeap - 6 months
I'm a big fan of spatial grid hashes to simplify situations like this. Nice to see other approaches. Iterative Insertion sorting would be easier to port to a compute shader than a spatial grid hash, so maybe this method is better if we get into the millions of objects range?
By @bee_rider - 6 months
Since the balls probably don’t move much per frame, should the list be considered “nearly sorted?”
By @yazzku - 6 months
Not mentioned is spatial hashing, which works well without complex data structures.

Also sad that you need all this complexity to test 25 balls in Javascript. 25^2 is a small number in C, especially when your balls fit in cache.

Still a good introduction to various algorithms, though.

By @sixthDot - 6 months
The title was curious to me because I expected more a post about the `intersects` function, e.g the pip algorithm... turns out it's more about the complexity involved by the number of objects to test, which in the end is also interesting.
By @zengid - 6 months
This is awesome, very beautiful and well written!

Are there other handy 2-d algorithms that are this well explained? I know redblobgames has a treasure trove too, but curious about more.

By @syntaxing - 6 months
Super interesting, my first thought before I read the article was why not a bloom filter but didn’t expect it to be “physical” collision
By @layer8 - 6 months
The animations don’t show on iOS Safari.
By @FrustratedMonky - 6 months
Very Nice animated examples