Collision detection: Difference between revisions

Content deleted Content added
"them" instead of "the character" to reduce repetition.
Update for clarity
 
(133 intermediate revisions by 74 users not shown)
Line 1:
{{aboutShort description|Term in computer science}}
{{About|collision detection in computational physicsgeometry|collision detection in computer networks|carrier Carrier-sense multiple access with collision detection}}
{{redirect|Hitbox}}
{{Multiple issues|{{Technical|section|date=March 2020}}
{{Tone|section|date=August 2014}}}}
 
'''Collision detection''' is the [[computational problem]] of detecting an [[Intersection (geometry)|intersection]] of two or more objects in virtual space. More precisely, it deals with the questions of ''if'', ''when'' and ''where'' two or more objects intersect. Collision detection is a classic problem of [[computational geometry]] with applications in [[computer graphics]], [[physical simulation]], [[video game]]s, [[robotics]] (including [[autonomous driving]]) and [[computational physics]]. Collision detection [[algorithm]]s can be divided into operating on 2D or 3D spatial objects.<ref>{{cite journal|url=https://hal.inria.fr/inria-00394479/document|title=Collision Detection for Deformable Objects|year=2005|doi=10.1111/j.1467-8659.2005.00829.x|last1=Teschner|first1=M.|last2=Kimmerle|first2=S.|last3=Heidelberger|first3=B.|last4=Zachmann|first4=G.|last5=Raghupathi|first5=L.|last6=Fuhrmann|first6=A.|last7=Cani|first7=M.-P.|last8=Faure|first8=F.|last9=Magnenat-Thalmann|first9=N.|last10=Strasser|first10=W.|last11=Volino|first11=P.|journal=Computer Graphics Forum|volume=24|pages=61–81|s2cid=1359430|citeseerx=10.1.1.58.2505}}</ref>
{{merge from|Hitbox|discuss=Talk:Collision detection#Video games#Proposed merge with Hitbox|date=March 2018}}
{{tone|date=August 2014}}
 
'''Collision detection''' is the computational problem of detecting the intersection of two or more objects. While collision detection is most often associated with its use in [[video game]]s and other [[computer simulations|physical simulations]], it also has applications in [[robotics]]. In addition to determining whether two objects have collided, collision detection systems may also calculate ''time of impact'' (TOI), and report a ''contact manifold'' (the set of intersecting points).<ref>Ericson, Christer. Real-time Collision Detection. Elsevier, 2005, p. 13.</ref> [[Collision response]] deals with simulating what happens when a collision is detected (see [[physics engine]], [[ragdoll physics]]). Solving collision detection problems requires extensive use of concepts from [[linear algebra]] and [[computational geometry]].
 
== Overview ==
[[Image:Billiards balls.jpg|right|200px|thumb|Billiards balls hitting each other in a virtual space are a classic example where collision detection computations are needed.]]Collision detection is closely linked to calculating the [[Euclidean distance|distance]] between objects, as two objects (or more) intersect when the distance between them reaches zero or even becomes negative.<ref>{{Cite book |url=https://www.csun.edu/~ctoth/Handbook/HDCG3.html |title=Handbook of discrete and computational geometry |date=2018 |publisher=CRC Press, Taylor & Francis Group, a Chapman & Hall book |isbn=978-1-4987-1139-5 |editor-last=Goodman |editor-first=Jacob E. |edition=3rd |series=Discrete mathematics and its applications |___location=Boca Raton London New York |chapter=39 |editor-last2=O'Rourke |editor-first2=Joseph |editor-last3=Tóth |editor-first3=Csaba D.}}</ref> Negative distance indicates that one object has penetrated another. Performing collision detection requires more context than just the distance between the objects.
[[Image:Billiards balls.jpg|right|200px|thumb|Billiards balls hitting each other are a classic example applicable within the science of collision detection.]]
In physical simulation, experiments, such as playing [[billiards]], are conducted. The [[physics]] of bouncing billiard balls are well understood, under the umbrella of [[rigid body motion]] and [[elastic collision]]s. An initial description of the situation would be given, with a very precise physical description of the billiard table and balls, as well as initial positions of all the balls. Given a force applied to the cue ball (probably resulting from a player hitting the ball with his or her cue stick), we want to calculate the trajectories, precise motion, and eventual resting places of all the balls with a [[computer program]]. A program to simulate this game would consist of several portions, one of which would be responsible for calculating the precise impacts between the billiard balls. This particular example also turns out to be [[condition number|ill conditioned]]: a small error in any calculation will cause drastic changes in the final position of the billiard balls.
 
Accurately identifying the points of contact on both objects' surfaces is also essential for the computation of a physically accurate [[collision response]]. The complexity of this task increases with the level of detail in the objects' representations: the more intricate the model, the greater the computational cost.<ref name=":col0">{{Cite book |last1=Andrews |first1=Sheldon |last2=Erleben |first2=Kenny |last3=Ferguson |first3=Zachary |chapter=Contact and friction simulation for computer graphics |date=2022-08-02 |title=ACM SIGGRAPH 2022 Courses |chapter-url=https://dl.acm.org/doi/10.1145/3532720.3535640 |language=en |publisher=ACM |pages=1–172 |doi=10.1145/3532720.3535640 |isbn=978-1-4503-9362-1}}</ref>
Video games have similar requirements, with some crucial differences. While physical simulation needs to simulate real-world physics as precisely as possible, video games need to simulate real-world physics in an ''acceptable'' way, in [[Real-time computing|real time]] and robustly. Compromises are allowed, so long as the resulting simulation is satisfying to the game players.
 
Collision detection frequently involves dynamic objects, adding a temporal dimension to distance calculations. Instead of simply measuring distance between static objects, collision detection algorithms often aim to determine whether the objects’ motion will bring them to a point in time when their distance is zero—an operation that adds significant computational overhead.<ref name=":col1">{{Cite book |last1=Hadap |first1=Sunil |last2=Eberle |first2=Dave |last3=Volino |first3=Pascal |last4=Lin |first4=Ming C. |last5=Redon |first5=Stephane |last6=Ericson |first6=Christer |chapter=Collision detection and proximity queries |date=2004-08-08 |title=ACM SIGGRAPH 2004 Course Notes |chapter-url=https://dl.acm.org/doi/10.1145/1103900.1103915 |language=en |publisher=ACM |pages=15 |doi=10.1145/1103900.1103915 |isbn=978-1-4503-7801-7}}</ref><ref name=":col0" />
== Collision detection in physical simulation ==
Physical simulators differ in the way they react on a collision. Some use the softness of the material to calculate a force, which will resolve the collision in the following time steps like it is in reality. Due to the low softness of some materials this is very CPU intensive. Some simulators estimate the time of collision by [[linear interpolation]], [[Rollback (data management)|roll back]] the simulation, and calculate the collision by the more abstract methods of [[conservation laws]].
 
In collision detection involving multiple objects, a naive approach would require detecting collisions for all pairwise combinations of objects. As the number of objects increases, the number of required comparisons grows rapidly: for <math>n</math> objects, <math display="">{n(n-1)}/{2}</math> intersection tests are needed with a naive approach. This quadratic growth makes such an approach computationally expensive as <math>n</math> increases.<ref name=":col1" /><ref name=":0">{{Cite book |last1=Cohen |first1=Jonathan D. |last2=Lin |first2=Ming C. |last3=Manocha |first3=Dinesh |last4=Ponamgi |first4=Madhav |chapter=I-COLLIDE: An interactive and exact collision detection system for large-scale environments |date=1995 |title=Proceedings of the 1995 symposium on Interactive 3D graphics - SI3D '95 |chapter-url=http://portal.acm.org/citation.cfm?doid=199404.199437 |language=en |publisher=ACM Press |pages=189–ff |doi=10.1145/199404.199437 |isbn=978-0-89791-736-0}}</ref>
Some iterate the linear interpolation ([[Newton's method]]) to calculate the time of collision with a much higher precision than the rest of the simulation. Collision detection utilizes time coherence to allow even finer time steps without much increasing CPU demand, such as in [[air traffic control]].
 
Due to the complexity mentioned above, collision detection is a computationally intensive process. Nevertheless, it is essential for interactive applications like video games, robotics, and real-time physics engines. To manage these computational demands, extensive efforts have gone into optimizing collision detection algorithms.
After an inelastic collision, special states of sliding and resting can occur and, for example, the [[Open Dynamics Engine]] uses constraints to simulate them. Constraints avoid inertia and thus instability. Implementation of rest by means of a [[scene graph]] avoids drift.
 
A commonly used approach towards accelerating the required computations is to divide the process into two phases: the '''broad phase''' and the '''narrow phase'''.<ref name=":col1" /><ref>{{Cite book |last1=Akenine-Möller |first1=Tomas |url=https://www.realtimerendering.com |title=Real-time rendering |last2=Haines |first2=Eric |last3=Hoffman |first3=Naty |last4=Pesce |first4=Angelo |last5=Iwanicki |first5=Michał |last6=Hillaire |first6=Sébastien |date=2018 |publisher=CRC Press, Taylor & Francis Group |isbn=978-1-138-62700-0 |edition=4th |series=An A K Peters book |___location=Boca Raton London New York}}</ref> The broad phase aims to answer the question of whether objects might collide, using a conservative but efficient approach to rule out pairs that clearly do not intersect, thus avoiding unnecessary calculations.
In other words, physical simulators usually function one of two ways, where the collision is detected ''[[Empirical evidence|a posteriori]]'' (after the collision occurs) or ''[[A priori and a posteriori|a priori]]'' (before the collision occurs). In addition to the ''a posteriori'' and ''a priori'' distinction, almost all modern collision detection algorithms are broken into a hierarchy of algorithms. Often the terms "discrete" and "continuous" are used rather than ''a posteriori'' and ''a priori''.
 
Objects that cannot be definitively separated in the broad phase are passed to the narrow phase. Here, more precise algorithms determine whether these objects actually intersect. If they do, the narrow phase often calculates the exact time and ___location of the intersection.
=== A posteriori (discrete) versus a priori (continuous) ===
{{Tone|article|date=July 2018}}
In the ''a posteriori'' case, we advance the physical simulation by a small time step, then check if any objects are intersecting, or are somehow so close to each other that we deem them to be intersecting. At each simulation step, a list of all intersecting bodies is created, and the positions and trajectories of these objects are somehow "fixed" to account for the collision. We say that this method is ''a posteriori'' because we typically miss the actual instant of collision, and only catch the collision after it has actually happened.
 
== Broad phase ==
In the ''a priori'' methods, we write a collision detection algorithm which will be able to predict very precisely the trajectories of the physical bodies. The instants of collision are calculated with high precision, and the physical bodies never actually interpenetrate. We call this ''a priori'' because we calculate the instants of collision before we update the configuration of the physical bodies.
This phase aims at quickly finding objects or parts of objects for which it can be quickly determined that no further collision test is needed. A useful property of such approach is that it is [[Output-sensitive algorithm|output sensitive]]. In the context of collision detection this means that the time complexity of the collision detection is proportional to the number of objects that are close to each other. An early example of that is the I-COLLIDE<ref name=":0" /> where the number of required narrow phase collision tests was <math>O(n + m)</math> where <math>n</math> is the number of objects and <math>m</math> is the number of objects at close proximity. This is a significant improvement over the quadratic complexity of the naive approach.
 
=== Spatial partitioning ===
The main benefits of the ''a posteriori'' methods are as follows. In this case, the collision detection algorithm need not be aware of the myriad of physical variables; a simple list of physical bodies is fed to the algorithm, and the program returns a list of intersecting bodies. The collision detection algorithm doesn't need to understand friction, elastic collisions, or worse, nonelastic collisions and deformable bodies. In addition, the ''a posteriori'' algorithms are in effect one dimension simpler than the ''a priori'' algorithms. Indeed, an ''a priori'' algorithm must deal with the time variable, which is absent from the ''a posteriori'' problem.
Several approaches can be grouped under the [[spatial partitioning]] umbrella, which includes [[octree]]s (for 3D), [[quadtree]]s (for 2D), [[binary space partitioning]] (or BSP trees) and other, similar approaches. If one splits space into a number of simple cells, and if two objects can be shown not to be in the same cell, then they need not be checked for intersection. Dynamic scenes and deformable objects require updating the partitioning which can add overhead.
 
On the other hand, ''a posteriori'' algorithms cause problems in the "fixing" step, where intersections (which aren't physically correct) need to be corrected. Moreover, if the discrete step is too large, the collision could go undetected, resulting in an object which passes through another if it is sufficiently fast or small.
 
The benefits of the ''a priori'' algorithms are increased fidelity and stability. It is difficult (but not completely impossible) to separate the physical simulation from the collision detection algorithm. However, in all but the simplest cases, the problem of determining ahead of time when two bodies will collide (given some initial data) has no closed form solution—a numerical [[Root-finding algorithm|root finder]] is usually involved.
 
Some objects are in ''resting contact'', that is, in collision, but neither bouncing off, nor interpenetrating, such as a vase resting on a table. In all cases, resting contact requires special treatment: If two objects collide (''a posteriori'') or slide (''a priori'') and their relative motion is below a threshold, friction becomes [[stiction]] and both objects are arranged in the same branch of the [[scene graph]].
 
===Bounding volume hierarchy===
== Optimization ==
[[Bounding volume hierarchy|Bounding Volume Hierarchy]] (BVH) is a tree structure over a set of [[#Bounding volumes|bounding volumes]]. Collision is determined by doing a tree traversal starting from the root. If the bounding volume of the root doesn't intersect with the object of interest, the traversal can be stopped. If, however there is an intersection, the traversal proceeds and checks the branches for each there is an intersection. Branches for which there is no intersection with the bounding volume can be culled from further intersection test. Therefore, multiple objects can be determined to not intersect at once. BVH can be used with deformable objects such as cloth or soft-bodies but the volume hierarchy has to be adjusted as the shape deforms. For deformable objects we need to be concerned about self-collisions or self intersections. BVH can be used for that end as well. Collision between two objects is computed by computing intersection between the bounding volumes of the root of the tree as there are collision we dive into the sub-trees that intersect. Exact collisions between the actual objects, or its parts (often triangles of a [[triangle mesh]]) need to be computed only between intersecting leaves.<ref>
The obvious approaches to collision detection for multiple objects are very slow.
{{cite journal |last1=Klosowski |first1=James T |last2=Held |first2=Martin |last3=Mitchell |first3=Joseph S.B. |last4=Sowizral |first4=Henry |last5=Zikan |first5=Karel |date=1998 |title=Efficient collision detection using bounding volume hierarchies of k-DOPs |journal=IEEE Transactions on Visualization and Computer Graphics |publisher=IEEE |volume=4 |issue=1 |pages=21–36 |doi=10.1109/2945.675649}}
[[Triangular number|Checking every object against every other object]] will, of course, work, but is too inefficient to be used when the number of objects is at all large. Checking objects with complex geometry against each other in the obvious way, by checking each face against each other face, is itself quite slow. Thus, considerable research has been applied to speed up the problem.
</ref> The same approach works for pair wise collision and self-collisions.
 
=== Exploiting temporal coherence ===
During the broad-phase, when the objects in the world move or deform, the data-structures used to cull collisions have to be updated. In cases where the changes between two frames or time-steps are small and the objects can be approximated well with [[axis-aligned bounding box]]es, the [[sweep and prune]] algorithm<ref name=":0" /> can be a suitable approach.
In many applications, the configuration of physical bodies from one time step to the next changes very little. Many of the objects may not move at all.
Algorithms have been designed so that the calculations done in a preceding time step can be reused in the current time step, resulting in faster completion of the calculation.
 
Several key observation make the implementation efficient: Two bounding-boxes intersect [[If and only if|if, and only if]], there is overlap along all three axes; overlap can be determined, for each axis separately, by sorting the intervals for all the boxes; and lastly, between two frames updates are typically small (making sorting algorithms optimized for almost-sorted lists suitable for this application). The algorithm keeps track of currently intersecting boxes, and as objects move, re-sorting the intervals helps keep track of the status.<ref>{{Cite book |last=Ericson |first=Christer |url=https://realtimecollisiondetection.net/books/rtcd/ |title=Real-time collision detection |date= 22 December 2004|publisher=Elsevier |isbn=978-1-55860-732-3 |edition=Nachdr. |series=Morgan Kaufmann series in interactive 3D technology |___location=Amsterdam Heidelberg |pages=329–338}}</ref>
At the coarse level of collision detection, the objective is to find pairs of objects which might potentially intersect. Those pairs will require further analysis. An early high performance algorithm for this was developed by [[Ming C. Lin]] at the [[University of California, Berkeley]] [http://www.cs.berkeley.edu/~jfc/mirtich/collDet.html], who suggested using [[axis-aligned bounding box]]es for all ''n'' bodies in the scene.
 
=== Pairwise pruning ===
Each box is represented by the product of three intervals (i.e., a box would be <math>I_1 \times I_2 \times I_3=[a_1,b_1] \times [a_2,b_2] \times [a_3,b_3]</math>.) A common algorithm for collision detection of bounding boxes is [[sweep and prune]]. We observe that two such boxes, <math>I_1 \times I_2 \times I_3</math> and <math>J_1 \times J_2 \times J_3</math> intersect if, and only if, <math>I_1</math> intersects <math>J_1</math>, <math>I_2</math> intersects <math>J_2</math> and <math>I_3</math> intersects <math>J_3</math>. We suppose that, from one time step to the next, <math>I_k</math> and <math>J_k</math> intersect, then it is very likely that at the next time step, they will still intersect. Likewise, if they did not intersect in the previous time step, then they are very likely to continue not to.
{{Multiple issues|{{Technical|section|date=March 2020}}
{{Tone|section|date=January 2024}}
{{Unreferenced section|date=July 2024}}|section=y}}
 
So we reduce the problem to that of tracking, from frame to frame, which intervals do intersect. We have three lists of intervals (one for each axis) and all lists are the same length (since each list has length <math>n</math>, the number of bounding boxes.) In each list, each interval is allowed to intersect all other intervals in the list. So for each list, we will have an <math>n \times n</math> [[matrix (math)|matrix]] <math>M=(m_{ij})</math> of zeroes and ones: <math>m_{ij}</math> is 1 if intervals <math>i</math> and <math>j</math> intersect, and 0 if they do not intersect.
 
By our assumption, the matrix <math>M</math> associated to a list of intervals will remain essentially unchanged from one time step to the next. To exploit this, the list of intervals is actually maintained as a list of labeled endpoints. Each element of the list has the coordinate of an endpoint of an interval, as well as a unique integer identifying that interval. Then, we [[sorting algorithm|sort]] the list by coordinates, and update the matrix <math>M</math> as we go. It's not so hard to believe that this algorithm will work relatively quickly if indeed the configuration of bounding boxes does not change significantly from one time step to the next.
 
In the case of deformable bodies such as cloth simulation, it may not be possible to use a more specific pairwise pruning algorithm as discussed below, and an ''n''-body pruning algorithm is the best that can be done.
 
If an upper bound can be placed on the velocity of the physical bodies in a scene, then pairs of objects can be pruned based on their initial distance and the size of the time step.
 
=== Pairwise pruning ===
Once we've selected a pair of physical bodies for further investigation, we need to check for collisions more carefully. However, in many applications, individual objects (if they are not too deformable) are described by a set of smaller primitives, mainly triangles. So now, we have two sets of triangles, <math>S={S_1,S_2,\dots,S_n}</math> and <math>T={T_1,T_2,\dots,T_n}</math> (for simplicity, we will assume that each set has the same number of triangles.)
 
The obvious thing to do is to check all triangles <math>S_j</math> against all triangles <math>T_k</math> for collisions, but this involves <math>n^2</math> comparisons, which is highly inefficient. If possible, it is desirable to use a pruning algorithm to reduce the number of pairs of triangles we need to check.
 
The most widely used family of algorithms is known as the ''hierarchical bounding volumes'' method. As a preprocessing step, for each object (in our example, <math>S</math> and <math>T</math>) we will calculate a [[bounding volume hierarchy|hierarchy of bounding volumes]]. Then, at each time step, when we need to check for collisions between <math>S</math> and <math>T</math>, the hierarchical bounding volumes are used to reduce the number of pairs of triangles under consideration. For simplicity, we will give an example using bounding spheres, although it has been noted that spheres are undesirable in many cases.{{Citation needed|date=June 2008}}
 
If <math>E</math> is a set of triangles, we can precalculatepre-calculate a bounding sphere <math>B(E)</math>. There are many ways of choosing <math>B(E)</math>, we only assume that <math>B(E)</math> is a sphere that completely contains <math>E</math> and is as small as possible.
 
Ahead of time, we can compute <math>B(S)</math> and <math>B(T)</math>. Clearly, if these two spheres do not intersect (and that is very easy to test), then neither do <math>S</math> and <math>T</math>. This is not much better than an ''n''-body pruning algorithm, however.
Line 68 ⟶ 55:
If <math>E={E_1,E_2,\dots,E_m}</math> is a set of triangles, then we can split it into two halves <math>L(E):={E_1,E_2,\dots,E_{m/2}}</math> and <math>R(E):={E_{m/2+1},\dots,E_{m-1},E_m}</math>. We can do this to <math>S</math> and <math>T</math>, and we can calculate (ahead of time) the bounding spheres <math>B(L(S)),B(R(S))</math> and <math>B(L(T)),B(R(T))</math>. The hope here is that these bounding spheres are much smaller than <math>B(S)</math> and <math>B(T)</math>. And, if, for instance, <math>B(S)</math> and <math>B(L(T))</math> do not intersect, then there is no sense in checking any triangle in <math>S</math> against any triangle in <math>L(T)</math>.
 
As a [[precomputation]], we can take each physical body (represented by a set of triangles) and recursively decompose it into a [[binary tree]], where each node <math>N</math> represents a set of triangles, and its two children represent <math>L(N)</math> and <math>R(N)</math>. At each node in the tree, we can precomputepre-compute the bounding sphere <math>B(N)</math>.
 
When the time comes for testing a pair of objects for collision, their bounding sphere tree can be used to eliminate many pairs of triangles.
Line 74 ⟶ 61:
Many variants of the algorithms are obtained by choosing something other than a sphere for <math>B(T)</math>. If one chooses [[axis-aligned bounding box]]es, one gets AABBTrees. [[Oriented bounding box]] trees are called OBBTrees. Some trees are easier to update if the underlying object changes. Some trees can accommodate higher order primitives such as [[Spline (mathematics)|spline]]s instead of simple triangles.
 
== Narrow phase ==
=== Exact pairwise collision detection ===
Objects that cannot be definitively separated in the broad phase are passed to the narrow phase. In this phase, the objects under consideration are relatively close to each other. Still, attempts to quickly determine if a full intersection is needed are employed first. This step is sometimes referred to as mid-phase.<ref name=":col1" /> Once these tests passed (e.g. the pair of objects may be colliding) more precise algorithms determine whether these objects actually intersect. If they do, the narrow phase often calculates the exact time and ___location of the intersection.
Once we're done pruning, we are left with a number of candidate pairs to check for exact collision detection.
 
===Bounding volumes===
A basic observation is that for any two [[convex set|convex]] objects which are disjoint, one can find a plane in space so that one object lies completely on one side of that plane, and the other object lies on the opposite side of that plane. This allows the development of very fast collision detection algorithms for convex objects.
A quick way to potentially avoid a needless expensive computation is to check if the bounding volume enclosing the two objects intersect. If they don't, there is no need to check the actual objects. However, if the [[bounding volume|bounding volumes]] do intersect, the more expensive computation has to be performed. In order for the bounding-volume test to add value, two properties need to be balanced: a) the cost of intersecting the bounding volume needs to be low and b) the bounding volume needs to be tight enough so that the number of 'false positive' intersection will be low. A false positive intersection in this case means that the bounding volumes intersect but the actual objects do not. Different bounding volume types offer different trade-offs for these properties.
 
[[Minimum bounding box#Axis-aligned minimum bounding box|Axis-Align Bounding Boxes (AABB)]] and [[cuboid]]s are popular due to their simplicity and quick intersection tests.<ref>{{cite web |author=Caldwell, Douglas R. |date=2005-08-29 |title=Unlocking the Mysteries of the Bounding Box |url=http://www.stonybrook.edu/libmap/coordinates/seriesa/no2/a2.htm |url-status=dead |archive-url=https://web.archive.org/web/20120728180104/http://www.stonybrook.edu/libmap/coordinates/seriesa/no2/a2.htm |archive-date=2012-07-28 |access-date=2014-05-13 |publisher=US Army Engineer Research & Development Center, Topographic Engineering Center, Research Division, Information Generation and Management Branch}}</ref> Bounding volumes such as [[Minimum bounding box#Arbitrarily oriented minimum bounding box|Oriented Bounding Boxes (OBB)]], [[Bounding volume#Common types|K-DOPs]] and Convex-hulls offer a tighter approximation of the enclosed shape at the expense of a more elaborate intersection test.
Early work in this area involved "[[Separating axis theorem|separating plane]]" methods. Two triangles collide essentially only when they can not be separated by a plane going through three vertices. That is, if the triangles are <math>{v_1,v_2,v_3}</math> and <math>{v_4,v_5,v_6}</math> where each <math>v_j</math> is a vector in <math>\Bbb R^3</math>, then we can take three vertices, <math>v_i,v_j,v_k</math>, find a plane going through all three vertices, and check to see if this is a separating plane. If any such plane is a separating plane, then the triangles are deemed to be disjoint. On the other hand, if none of these planes are separating planes, then the triangles are deemed to intersect. There are twenty such planes.
 
Bounding volumes are typically used in the early (pruning) stage of collision detection, so that only objects with overlapping bounding volumes need be compared in detail.<ref>{{cite journal |author=Gan B, Dong Q |date=2022 |title=An improved optimal algorithm for collision detection of hybrid hierarchical bounding box |url=https://www.researchgate.net/publication/348937861 |journal=Evolutionary Intelligence |volume=15 |issue=4 |pages=2515–2527 |doi=10.1007/s12065-020-00559-6}}</ref> Computing collision or overlap between bounding volumes involves additional computations, therefore, in order for it to beneficial we need the bounding volume to be relatively tight and the computation overhead to due the collisions to be low.
If the triangles are coplanar, this test is not entirely successful. One can add some extra planes, for instance, planes that are normal to triangle edges, to fix the problem entirely. In other cases, objects that meet at a flat face must necessarily also meet at an angle elsewhere, hence the overall collision detection will be able to find the collision.
 
=== Exact pairwise collision detection ===
Better methods have since been developed. Very fast algorithms are available for finding the closest points on the surface of two convex polyhedral objects. Early work by [[Ming C. Lin]]<ref>{{cite paper |author=Lin, Ming C|title=Efficient Collision Detection for Animation and Robotics (thesis)|year=1993|publisher=University of California, Berkeley|url=https://wwwx.cs.unc.edu/~geom/papers/documents/dissertations/lin93.pdf}}
{{how-to|section|date=January 2024}}
</ref> used a variation on the [[simplex algorithm]] from [[linear programming]]. The [[Gilbert-Johnson-Keerthi distance algorithm]] has superseded that approach. These algorithms approach constant time when applied repeatedly to pairs of stationary or slow-moving objects, when used with starting points from the previous collision check.
 
Objects for which pruning approaches could not rule out the possibility of a collision have to undergo an exact collision detection computation.
 
==== Collision detection between convex objects ====
According to the [[Hyperplane separation theorem|separating planes theorem]], for any two disjoint [[convex set|convex]] objects, there exists a plane so that one object lies completely on one side of that plane, and the other object lies on the opposite side of that plane. This property allows the development of efficient collision detection algorithms between convex objects. Several algorithms are available for finding the closest points on the surface of two convex polyhedral objects - and determining collision. Early work by [[Ming C. Lin]]<ref name=":1">{{cite web |author=Lin, Ming C |year=1993 |title=Efficient Collision Detection for Animation and Robotics (thesis) |url=https://wwwx.cs.unc.edu/~geom/papers/documents/dissertations/lin93.pdf |archive-url=https://web.archive.org/web/20140728124049/https://wwwx.cs.unc.edu/~geom/papers/documents/dissertations/lin93.pdf |archive-date=2014-07-28 |publisher=University of California, Berkeley}}
</ref> that used a variation on the [[simplex algorithm]] from [[linear programming]] and the [[Gilbert-Johnson-Keerthi distance algorithm]]<ref>{{Cite journal |last1=Gilbert |first1=E.G. |last2=Johnson |first2=D.W. |last3=Keerthi |first3=S.S. |date=1988 |title=A fast procedure for computing the distance between complex objects in three-dimensional space |url=https://graphics.stanford.edu/courses/cs448b-00-winter/papers/gilbert.pdf |journal=IEEE Journal on Robotics and Automation |volume=4 |issue=2 |pages=193–203 |doi=10.1109/56.2083}}</ref> are two such examples. These algorithms approach constant time when applied repeatedly to pairs of stationary or slow-moving objects, and every step is initialized from the previous collision check.<ref name=":1" />
 
The end result of all this algorithmic work is that collision detection can be done efficiently for thousands of moving objects in real time on typical personal computers and game consoles.
 
=== A priori pruning ===
Line 95 ⟶ 89:
When it comes to the exact pairwise collision detection, this is highly trajectory dependent, and one almost has to use a numerical [[root-finding algorithm]] to compute the instant of impact.
 
As an example, consider two triangles moving in time <math>{v_1(t),v_2(t),v_3(t)}</math> and <math>{v_4(t),v_5(t),v_6(t)}</math>. At any point in time, the two triangles can be checked for intersection using the twenty planes previously mentioned. However, we can do better, since these twenty planes can all be tracked in time. If <math>P(u,v,w)</math> is the plane going through points <math>u,v,w</math> in <math>\Bbbmathbb R^3</math> then there are twenty planes <math>P(v_i(t),v_j(t),v_k(t))</math> to track. Each plane needs to be tracked against three vertices, this gives sixty values to track. Using a root finder on these sixty functions produces the exact collision times for the two given triangles and the two given trajectory. We note here that if the trajectories of the vertices are assumed to be linear polynomials in <math>t</math> then the final sixty functions are in fact cubic polynomials, and in this exceptional case, it is possible to locate the exact collision time using the formula for the roots of the cubic. Some numerical analysts suggest that using the formula for the roots of the cubic is not as numerically stable as using a root finder for polynomials.{{Citation needed|date=June 2008}}
 
=== Spatial partitioning ===
Alternative algorithms are grouped under the [[spatial partitioning]] umbrella, which includes [[octree]]s, [[binary space partitioning]] (or BSP trees) and other, similar approaches. If one splits space into a number of simple cells, and if two objects can be shown not to be in the same cell, then they need not be checked for intersection. Since BSP trees can be precomputed, that approach is well suited to handling walls and fixed obstacles in games. These algorithms are generally older than the algorithms described above.
 
===Bounding boxes===
[[Bounding box]]es (or [[bounding volume]]s) are most often a 2D rectangle or 3D [[cuboid]], but other shapes are possible.
The bounding diamond, the minimum bounding parallelogram, the convex hull, the bounding circle or bounding ball, and the bounding ellipse have all been tried, but bounding boxes remain the most popular due to their simplicity.<ref>{{cite paper |
url=http://www.stonybrook.edu/libmap/coordinates/seriesa/no2/a2.htm |
title=Unlocking the Mysteries of the Bounding Box |
date=2005-08-29 |
author=Caldwell, Douglas R. |
publisher=US Army Engineer Research & Development Center, Topographic Engineering Center, Research Division, Information Generation and Management Branch}}</ref> Bounding boxes are typically used in the early (pruning) stage of collision detection, so that only objects with overlapping bounding boxes need be compared in detail.
 
=== Triangle centroid segments ===
A [[triangle mesh]] object is commonly used in 3D body modeling. Normally the collision function is a triangle to triangle intercept or a bounding shape associated with the mesh. A triangle centroid is a center of mass ___location such that it would balance on a pencil tip. The simulation need only add a centroid dimension to the physics parameters. Given centroid points in both object and target it is possible to define the line segment connecting these two points.
 
The position vector of the centroid of a triangle is the average of the position vectors of its vertices. So if its vertices have Cartesian coordinates <math>(x_1,y_1,z_1)</math>, <math>(x_2,y_2,z_2)</math> and <math>(x_3,y_3,z_3)</math> then the centroid is <math>\left(\frac{(x_1+x_2+x_3)}{3},\frac{(y_1+y_2+y_3)}{3},\frac{(z_1+z_2+z_3)}{3}\right)</math>.
 
Here is the function for a line segment distance between two 3D points. <math>\mathrm{distance} = \sqrt{(z_2 - z_1)^2 + (x_2 - x_1)^2 + (y_2 - y_1)^2}</math>
Line 118 ⟶ 100:
Here the length/distance of the segment is an adjustable "hit" criteria size of segment. As the objects approach the length decreases to the threshold value. A triangle sphere becomes the effective geometry test. A sphere centered at the centroid can be sized to encompass all the triangle's vertices.
 
== Video gamesUsage ==
Video games have to split their very limited computing time between several tasks. Despite this resource limit, and the use of relatively primitive collision detection algorithms, programmers have been able to create believable, if inexact, systems for use in games {{Citation needed|date=August 2014}}.
 
=== Collision detection in computer simulation ===
For a long time, video games had a very limited number of objects to treat, and so checking all pairs was not a problem. In two-dimensional games, in some cases, the hardware was able to efficiently detect and report overlapping pixels between [[sprite (computer graphics)|sprite]]s on the screen.<ref>{{Cite web|url=http://amigadev.elowar.com/read/ADCD_2.1/Hardware_Manual_guide/node0004.html#line95|title=Components of the Amiga: The MC68000 and the Amiga Custom Chips|last=|first=|date=|website=|series=|at=Chapter 1|type=Reference manual|archive-url=https://web.archive.org/web/20180717093216id_/http://amigadev.elowar.com/read/ADCD_2.1/Hardware_Manual_guide/node0004.html#line95|archive-date=2018-07-17|dead-url=no|access-date=2018-07-17|quote=Additionally, you can use system hardware to detect collisions between objects and have your program react to such collisions.|edition=2.1}}</ref> In other cases, simply tiling the screen and binding each ''sprite'' into the tiles it overlaps provides sufficient pruning, and for pairwise checks, bounding rectangles or circles called [[hitbox]]es are used and deemed sufficiently accurate.
{{unreferenced section|date=January 2024}}
Physical simulators differ in the way they react on a collision. Some use the softness of the material to calculate a force, which will resolve the collision in the following time steps like it is in reality. This is very CPU intensive for low softness materials. Some simulators estimate the time of collision by [[linear interpolation]], [[Rollback (data management)|roll back]] the simulation, and calculate the collision by the more abstract methods of [[conservation laws]].
 
Some iterate the linear interpolation ([[Newton's method]]) to calculate the time of collision with a much higher precision than the rest of the simulation. Collision detection utilizes time coherence to allow even finer time steps without much increasing CPU demand, such as in [[air traffic control]].
 
After an inelastic collision, special states of sliding and resting can occur and, for example, the [[Open Dynamics Engine]] uses constraints to simulate them. Constraints avoid inertia and thus instability. Implementation of rest by means of a [[scene graph]] avoids drift.
 
In other words, physical simulators usually function one of two ways: where the collision is detected ''[[Empirical evidence|a posteriori]]'' (after the collision occurs) or ''[[A priori and a posteriori|a priori]]'' (before the collision occurs). In addition to the ''a posteriori'' and ''a priori'' distinction, almost all modern collision detection algorithms are broken into a hierarchy of algorithms. Often the terms "discrete" and "continuous" are used rather than ''a posteriori'' and ''a priori''.
 
==== ''A posteriori'' (discrete) versus ''a priori'' (continuous) ====
{{Unreferenced section|date=August 2022}}
In the ''a posteriori'' case, the physical simulation is advanced by a small step, then checked to see if any objects are intersecting or visibly considered intersecting. At each simulation step, a list of all intersecting bodies is created, and the positions and trajectories of these objects are "fixed" to account for the collision. This method is called ''a posteriori'' because it typically misses the actual instant of collision, and only catches the collision after it has actually happened.
 
In the ''a priori'' methods, there is a collision detection algorithm which will be able to predict very precisely the trajectories of the physical bodies. The instants of collision are calculated with high precision, and the physical bodies never actually interpenetrate. This is called ''a priori'' because the collision detection algorithm calculates the instants of collision before it updates the configuration of the physical bodies.
 
The main benefits of the ''a posteriori'' methods are as follows. In this case, the collision detection algorithm need not be aware of the myriad of physical variables; a simple list of physical bodies is fed to the algorithm, and the program returns a list of intersecting bodies. The collision detection algorithm doesn't need to understand friction, elastic collisions, or worse, nonelastic collisions and deformable bodies. In addition, the ''a posteriori'' algorithms are in effect one dimension simpler than the ''a priori'' algorithms. An ''a priori'' algorithm must deal with the time variable, which is absent from the ''a posteriori'' problem.
 
On the other hand, ''a posteriori'' algorithms cause problems in the "fixing" step, where intersections (which aren't physically correct) need to be corrected. Moreover, if the discrete step is too large, the collision could go undetected, resulting in an object which passes through another if it is sufficiently fast or small.
 
The benefits of the ''a priori'' algorithms are increased fidelity and stability. It is difficult (but not completely impossible) to separate the physical simulation from the collision detection algorithm. However, in all but the simplest cases, the problem of determining ahead of time when two bodies will collide (given some initial data) has no closed form solution—a numerical [[Root-finding algorithm|root finder]] is usually involved.
 
Some objects are in ''resting contact'', that is, in collision, but neither bouncing off, nor interpenetrating, such as a vase resting on a table. In all cases, resting contact requires special treatment: If two objects collide (''a posteriori'') or slide (''a priori'') and their relative motion is below a threshold, friction becomes [[stiction]] and both objects are arranged in the same branch of the [[scene graph]].
 
=== Video games ===
Video games have to split their very limited computing time between several tasks. Despite this resource limit, and the use of relatively primitive collision detection algorithms, programmers have been able to create believable, if inexact, systems for use in games.{{Citation needed|date=August 2014}}
 
For a long time, video games had a very limited number of objects to treat, and so checking all pairs was not a problem. In two-dimensional games, in some cases, the hardware was able to efficiently detect and report overlapping pixels between [[sprite (computer graphics)|sprite]]s on the screen.<ref>{{Cite web|url=http://amigadev.elowar.com/read/ADCD_2.1/Hardware_Manual_guide/node0004.html#line95|title=Components of the Amiga: The MC68000 and the Amiga Custom Chips|at=Chapter 1|type=Reference manual|archive-url=https://web.archive.org/web/20180717093216/http://amigadev.elowar.com/read/ADCD_2.1/Hardware_Manual_guide/node0004.html#line95|archive-date=2018-07-17|url-status=live|access-date=2018-07-17|quote=Additionally, you can use system hardware to detect collisions between objects and have your program react to such collisions.|edition=2.1}}</ref> In other cases, simply tiling the screen and binding each ''sprite'' into the tiles it overlaps provides sufficient pruning, and for pairwise checks, bounding rectangles or circles called [[hitbox]]es are used and deemed sufficiently accurate.
 
Three-dimensional games have used spatial partitioning methods for <math>n</math>-body pruning, and for a long time used one or a few spheres per actual 3D object for pairwise checks. Exact checks are very rare, except in games attempting to [[Simulation game|simulate]] reality closely. Even then, exact checks are not necessarily used in all cases.
Line 127 ⟶ 135:
Because games do not need to mimic actual physics, stability is not as much of an issue. Almost all games use ''a posteriori'' collision detection, and collisions are often resolved using very simple rules. For instance, if a character becomes embedded in a wall, they might be simply moved back to their last known good ___location. Some games will calculate the distance the character can move before getting embedded into a wall, and only allow them to move that far.
 
In many cases for video games, approximating the characters by a point is sufficient for the purpose of collision detection with the environment. In this case, [[binary space partitionpartitioning]]ing trees provide a viable, efficient and simple algorithm for checking if a point is embedded in the scenery or not. Such a data structure can also be used to handle "resting position" situation gracefully when a character is running along the ground. Collisions between characters, and collisions with projectiles and hazards, are treated separately.
 
A robust simulator is one that will react to any input in a reasonable way. For instance, if we imagine a high speed [[Racing game|racecar video game]], it is conceivable that the cars would advance a substantial distance along the race track from one simulation step to the next. If there is a shallow obstacle on the track (such as a brick wall), it is not entirely unlikely that the car will completely leap over it, and this is very undesirable. In other instances, the "fixing" that posteriori algorithms require isn't implemented correctly, resulting in [[software bug|bug]]s that can trap characters in walls or allow them to pass through them and fall into an endless void where there may or may not be a deadly [[bottomless pit (video gaming)|bottomless pit]], sometimes referred to as "black hell", "blue hell", or "green hell", depending on the predominant color. These are the hallmarks of a failing collision detection and physical simulation system. ''[[Big Rigs: Over the Road Racing]]'' is an infamous example of a game with a failing or possibly missing collision detection system.
 
==== Hitbox ====<!-- Deleted image removed: [[File:GearheadsCollisionBoxSize.png|thumb|A [[Debug menu|debug]] dialogue box in ''[[Gearheads (video game)|Gearheads]]'' controlling an object's hitbox {{Deletable file-caption|Tuesday, 9 July 2024|F7}}]] -->
<!-- Deleted image removed: [[File:GearheadsCollisionBox.png|thumb|The hitbox of a ''[[Gearheads (video game)|Gearheads]]'' toy, controlled by the above screen {{Deletable file-caption|Tuesday, 9 July 2024|F7}}]] -->
 
A '''hitbox''' is an invisible shape commonly used in [[video game]]s for real-time collision detection; it is a type of bounding box. It is often a rectangle (in 2D games) or [[cuboid]] (in 3D) that is attached to and follows a point on a visible object (such as a model or a sprite). Circular or spheroidial shapes are also common, though they are still most often called "boxes". It is common for animated objects to have hitboxes attached to each moving part to ensure accuracy during motion.<ref>{{cite web|title=Hitbox|work=Valve Developer Community|url=http://developer.valvesoftware.com/wiki/Hitbox|publisher=[[Valve Corporation|Valve]]|access-date=18 September 2011}}</ref>{{Unreliable source?|date=March 2018|Wikis are not suitable sources.}}
 
Hitboxes are used to detect "one-way" collisions such as a character being hit by a punch or a bullet. They are unsuitable for the detection of collisions with feedback (e.g. bumping into a wall) due to the difficulty experienced by both humans and [[Artificial intelligence (video games)|AI]] in managing a hitbox's ever-changing locations; these sorts of collisions are typically handled with much simpler [[axis-aligned bounding box]]es instead. Players may use the term "hitbox" to refer to these types of interactions regardless.
 
A '''hurtbox''' is a hitbox used to detect incoming sources of damage. In this context, the term ''hitbox'' is typically reserved for those which deal damage. For example, an attack may only land if the hitbox around an attacker's punch connects with one of the opponent's hurtboxes on their body, while opposing hitboxes colliding may result in the players trading or cancelling blows, and opposing hurtboxes do not interact with each other. The term is not standardized across the industry; some games reverse their definitions of ''hitbox'' and ''hurtbox'', while others only use "hitbox" for both sides.
A robust simulator is one that will react to any input in a reasonable way. For instance, if we imagine a high speed [[Racing game|racecar video game]], from one simulation step to the next, it is conceivable that the cars would advance a substantial distance along the race track. If there is a shallow obstacle on the track (such as a brick wall), it is not entirely unlikely that the car will completely leap over it, and this is very undesirable. In other instances, the "fixing" that posteriori algorithms require isn't implemented correctly, and characters find themselves embedded in walls, or falling off into a deep void, sometimes referred to as "black hell", "blue hell", or "green hell", depending on the predominant color. These are the hallmarks of a failing collision detection and physical simulation system. ''[[Big Rigs: Over the Road Racing]]'' is an infamous example of a game with a collision detection system failing, or not being present at all.
 
==See also==
{{div col}}
*[[Hit-testing]]
* [[BoundingChazelle volumepolyhedron]]
* [[GameCollision physicsresponse]]
* [[Hit-testing]]
*[[Gilbert–Johnson–Keerthi distance algorithm]]
* [[Bounding volume]]
*[[Minkowski Portal Refinement]]
* [[PhysicsGame enginephysics]]
* [[Lubachevsky–StillingerGilbert–Johnson–Keerthi distance algorithm]]
* [[Minkowski Portal Refinement]]
*[[Ragdoll physics]]
* [[Physics engine]]
* [[Lubachevsky–Stillinger algorithm]]
* [[Ragdoll physics]]
{{div col end}}
 
==References==
Line 145 ⟶ 166:
 
==External links==
 
* [http://gamma.cs.unc.edu/research/collision/ University of North Carolina at Chapel Hill collision detection research web site]
* [https://css-tricks.com/worlds-collide-keyframe-collision-detection-using-style-queries/ Collision detection in CSS animations]
* [http://gamma.cs.unc.edu/research/collision/ University of North Carolina at Chapel Hill collision detection research website]
* [http://web.comlab.ox.ac.uk/oucl/work/stephen.cameron/distances/ Prof. Steven Cameron (Oxford University) web site on collision detection]
* [http://demonstrations.wolfram.com/HowToAvoidACollision/ How to Avoid a Collision] by George Beck, [[Wolfram Demonstrations Project]].
* {{usurped|1=[https://web.archive.org/web/20130108211242/http://geomalgorithms.com/a08-_containers.html Bounding boxes and their usage]}}
* [http://programmerart.weebly.com/separating-axis-theorem.html Separating Axis Theorem]
* [https://docs.unity3d.com/ScriptReference/Collision.html Unity 3D Collision]
* [https://docs.godotengine.org/en/3.1/tutorials/physics/physics_introduction.html Godot Physics Collision]
 
{{Authority control}}
 
{{DEFAULTSORT:Collision Detection}}
[[Category:Computational physicsgeometry]]
[[Category:Computer physics enginesgraphics]]
[[Category:Video game development]]
[[Category:Computer physics engines]]
[[Category:Robotics engineering]]