LearnOpenGL

Translation in progress of learnopengl.com.
git clone https://git.mtkn.jp/LearnOpenGL
Log | Files | Refs

Collision-detection.html (12786B)


      1     <h1 id="content-title">Collision detection</h1>
      2 <h1 id="content-url" style='display:none;'>In-Practice/2D-Game/Collisions/Collision-detection</h1>
      3 <p>
      4   When trying to determine if a collision occurs between two objects, we generally do not use the vertex data of the objects themselves since these objects often have complicated shapes; this in turn makes the collision detection complicated. For this reason, it is a common practice to use more simple shapes (that usually have a nice mathematical definition) for collision detection that we <em>overlay</em> on top of the original object. We then check for collisions based on these simple shapes; this makes the code easier and saves a lot of performance. A few examples of such <def>collision shapes</def> are circles, spheres, rectangles, and boxes; these are a lot simpler to work with compared to arbitrary meshes with hundreds of triangles.
      5 </p>
      6 
      7 <p>
      8   While the simple shapes do give us easier and more efficient collision detection algorithms, they share a common disadvantage in that these shapes usually do not fully surround the object. The effect is that a collision may be detected that didn't really collide with the actual object; one should always keep in mind that these shapes are just approximations of the real shapes.  
      9 </p>
     10 
     11 <h2>AABB - AABB collisions</h2>  
     12 <p>
     13   AABB stands for <def>axis-aligned bounding box</def>, a rectangular collision shape aligned to the base axes of the scene, which in 2D aligns to the x and y axis. Being axis-aligned means the rectangular box has no rotation and its edges are parallel to the base axes of the scene (e.g. left and right edge are parallel to the y axis). The fact that these boxes are always aligned to the axes of the scene makes calculations easier. Here we surround the ball object with an AABB:
     14 </p>
     15 
     16 <img src="/img/in-practice/breakout/collisions_ball_aabb.png" alt="AABB on top of ball in OpenGL"/>
     17 
     18 
     19 
     20 <p>
     21   Almost all the objects in Breakout are rectangular based objects, so it makes perfect sense to use axis aligned bounding boxes for detecting collisions. This is exactly what we're going to do.
     22 </p>
     23 
     24 <p>
     25   Axis aligned bounding boxes can be defined in several ways. One of them is to define an AABB by a top-left and a bottom-right position. The <fun>GameObject</fun> class that we defined already contains a top-left position (its <var>Position</var> vector), and we can easily calculate its bottom-right position by adding its size to the top-left position vector (<var>Position</var><code> + </code><var>Size</var>). Effectively, each <fun>GameObject</fun> contains an AABB that we can use for collisions.
     26 </p>
     27 
     28 <p>
     29   So how do we check for collisions? A collision occurs when two collision shapes enter each other's regions e.g. the shape that determines the first object is in some way inside the shape of the second object. For AABBs this is quite easy to determine due to the fact that they're aligned to the scene's axes: we check for each axis if the two object' edges on that axis overlap. So we check if the horizontal edges overlap, and if the vertical edges overlap of both objects. If both the horizontal <strong>and</strong> vertical edges overlap we have a collision.
     30 </p>
     31 
     32 <img src="/img/in-practice/breakout/collisions_overlap.png" class="clean" alt="Image of overlapping edges of AABB"/>
     33 
     34 <p>
     35   Translating this concept to code is relatively straightforward. We check for overlap on both axes and if so, return a collision:
     36 </p>
     37 
     38 <pre><code>
     39 bool CheckCollision(GameObject &one, GameObject &two) // AABB - AABB collision
     40 {
     41     // collision x-axis?
     42     bool collisionX = one.Position.x + one.Size.x &gt;= two.Position.x &&
     43         two.Position.x + two.Size.x &gt;= one.Position.x;
     44     // collision y-axis?
     45     bool collisionY = one.Position.y + one.Size.y &gt;= two.Position.y &&
     46         two.Position.y + two.Size.y &gt;= one.Position.y;
     47     // collision only if on both axes
     48     return collisionX && collisionY;
     49 }  
     50 </code></pre>
     51 
     52 <p>
     53   We check if the right side of the first object is greater than the left side of the second object <strong>and</strong> if the second object's right side is greater than the first object's left  side; similarly for the vertical axis. If you have trouble visualizing this, try to draw the edges/rectangles on paper and determine this for yourself.
     54 </p>
     55 
     56 <p>
     57   To keep the collision code a bit more organized we add an extra function to the <fun>Game</fun> class:
     58 </p>
     59 
     60 <pre><code>
     61 class Game
     62 {
     63     public:
     64         [...]
     65         void DoCollisions();
     66 };
     67 </code></pre>
     68 
     69 <p>
     70   Within <fun>DoCollisions</fun>, we check for collisions between the ball object and each brick of the level. If we detect a collision, we set the brick's <var>Destroyed</var> property to <code>true</code>, which instantly stops the level from rendering this brick:
     71 </p>
     72 
     73 <pre><code>
     74 void Game::DoCollisions()
     75 {
     76     for (GameObject &box : this-&gt;Levels[this-&gt;Level].Bricks)
     77     {
     78         if (!box.Destroyed)
     79         {
     80             if (CheckCollision(*Ball, box))
     81             {
     82                 if (!box.IsSolid)
     83                     box.Destroyed = true;
     84             }
     85         }
     86     }
     87 }  
     88 </code></pre>
     89 
     90 <p>
     91   Then we also need to update the game's <fun>Update</fun> function:
     92 </p>
     93 
     94 <pre><code>
     95 void Game::Update(float dt)
     96 {
     97     // update objects
     98     Ball->Move(dt, this->Width);
     99     // check for collisions
    100     this->DoCollisions();
    101 }  
    102 </code></pre>
    103 
    104 
    105 <p>
    106   If we run the code now, the ball should detect collisions with each of the bricks and if the brick is not solid, the brick is destroyed. If you run the game now it'll look something like this:
    107 </p>
    108 
    109 <div class="video paused" onclick="ClickVideo(this)">
    110   <video width="600" height="450" loop>
    111     <source src="/video/in-practice/breakout/collisions.mp4" type="video/mp4" />
    112     <img src="/img/in-practice/breakout/collisions.png" class="clean"/>
    113   </video>
    114 </div>
    115 
    116 <p>
    117   While the collision detection does work, it's not very precise since the ball's rectangular collision shape collides with most of the bricks without the ball directly touching them. Let's see if we can figure out a more precise collision detection technique.
    118 </p>
    119 
    120 <h2>AABB - Circle collision detection</h2>
    121 <p>
    122   Because the ball is a circle-like object, an AABB is probably not the best choice for the ball's collision shape. The collision code thinks the ball is a rectangular box, so the ball often collides with a brick even though the ball sprite itself isn't yet touching the brick.
    123 </p>
    124 
    125 <img src="/img/in-practice/breakout/collisions_ball_aabb_touch.png" alt="Ball colliding with brick as an AABB"/>
    126 
    127 <p>
    128   It makes much more sense to represent the ball with a circle collision shape instead of an AABB. For this reason we included a <var>Radius</var> variable within the ball object. To define a circle collision shape, all we need is a position vector and a radius.
    129 </p>
    130 
    131   <img src="/img/in-practice/breakout/collisions_circle.png" alt="Ball circular collision shape"/>
    132 
    133 <p>
    134   This does mean we have to update the detection algorithm since it currently only works between two AABBs. Detecting collisions between a circle and a rectangle is a bit more complicated, but the trick is as follows: we find the point on the AABB that is closest to the circle, and if the distance from the circle to this point is less than its radius, we have a collision.
    135 </p>
    136   
    137   <p>
    138     The difficult part is getting this closest point \(\color{red}{\bar{P}}\) on the AABB. The following image shows how we can calculate this point for any arbitrary AABB and circle:
    139   </p>
    140 
    141   <img src="/img/in-practice/breakout/collisions_aabb_circle.png" class="clean" alt="AABB - Circle collision detection"/>
    142     
    143 <p>
    144    We first need to get the difference vector between the ball's center \(\color{blue}{\bar{C}}\) and the AABB's center \(\color{green}{\bar{B}}\) to obtain \(\color{purple}{\bar{D}}\). What we then need to do is <def>clamp</def> this vector \(\color{purple}{\bar{D}}\) to the AABB's half-extents \(\color{orange}{{w}}\) and \(\color{teal}{\bar{h}}\) and add it to \(\color{green}{\bar{B}}\). The half-extents of a rectangle are the distances between the rectangle's center and its edges: its size divided by two. This returns a position vector that is always located somewhere at the edge of the AABB (unless the circle's center is inside the AABB).
    145 </p>
    146     
    147 <note>
    148   A clamp operation <strong>clamps</strong> a value to a value within a given range. This is often expressed as:
    149   
    150 <pre><code>
    151 float clamp(float value, float min, float max) {
    152     return std::max(min, std::min(max, value));
    153 }  
    154 </code></pre>
    155   
    156   For example, a value of <code>42.0f</code> is clamped to <code>6.0f</code> with a range of <code>3.0f</code> to <code>6.0f</code>, and a value of <code>4.20f</code> would be clamped to <code>4.20f</code>.  <br/>
    157   
    158   Clamping a 2D vector means we clamp both its <code>x</code> and its <code>y</code> component within the given range.
    159 </note>
    160     
    161 <p>
    162    This clamped vector \(\color{red}{\bar{P}}\) is then the closest point from the AABB to the circle.  What we then need to do is calculate a new difference vector \(\color{purple}{\bar{D'}}\) that is the difference between the circle's center \(\color{blue}{\bar{C}}\) and the vector \(\color{red}{\bar{P}}\).
    163 </p>
    164     
    165     <img src="/img/in-practice/breakout/collisions_aabb_circle_radius_compare.png" class="clean" alt="Calculating difference vector D' to get distance between circle and closest point AABB"/>
    166       
    167 <p>
    168    Now that we have the vector \(\color{purple}{\bar{D'}}\), we can compare its length to the radius of the circle. If the length of \(\color{purple}{\bar{D'}}\) is less than the circle's radius, we have a collision.
    169 </p>
    170     
    171 <p>
    172   This is all expressed in code as follows:
    173 </p>
    174     
    175 <pre><code>
    176 bool CheckCollision(BallObject &one, GameObject &two) // AABB - Circle collision
    177 {
    178     // get center point circle first 
    179     glm::vec2 center(one.Position + one.Radius);
    180     // calculate AABB info (center, half-extents)
    181     glm::vec2 aabb_half_extents(two.Size.x / 2.0f, two.Size.y / 2.0f);
    182     glm::vec2 aabb_center(
    183         two.Position.x + aabb_half_extents.x, 
    184         two.Position.y + aabb_half_extents.y
    185     );
    186     // get difference vector between both centers
    187     glm::vec2 difference = center - aabb_center;
    188     glm::vec2 clamped = glm::clamp(difference, -aabb_half_extents, aabb_half_extents);
    189     // add clamped value to AABB_center and we get the value of box closest to circle
    190     glm::vec2 closest = aabb_center + clamped;
    191     // retrieve vector between center circle and closest point AABB and check if length &lt;= radius
    192     difference = closest - center;
    193     return glm::length(difference) &lt; one.Radius;
    194 }      
    195 </code></pre>
    196 
    197 <p>
    198   We create an overloaded function for <fun>CheckCollision</fun> that specifically deals with the case between a <fun>BallObject</fun> and a <fun>GameObject</fun>. Because we did not store the collision shape information in the objects themselves we have to calculate them: first the center of the ball is calculated, then the AABB's half-extents and its center.
    199 </p>
    200       
    201 <p>
    202   Using these collision shape attributes we calculate vector \(\color{purple}{\bar{D}}\) as <var>difference</var> that we clamp to <var>clamped</var> and add to the AABB's center to get point \(\color{red}{\bar{P}}\) as <var>closest</var>. Then we calculate the difference vector \(\color{purple}{\bar{D'}}\) between <var>center</var> and <var>closest</var> and return whether the two shapes collided or not.
    203 </p>
    204       
    205 <p>
    206   Since we previously called <fun>CheckCollision</fun> with the ball object as its first argument, we do not have to change any code since the overloaded version of <fun>CheckCollision</fun> now automatically applies. The result is now a much more precise collision detection algorithm:
    207 </p>
    208 
    209 <div class="video paused" onclick="ClickVideo(this)">
    210   <video width="600" height="450" loop>
    211     <source src="/video/in-practice/breakout/collisions_circle.mp4" type="video/mp4" />
    212     <img src="/img/in-practice/breakout/collisions_precise.png" class="clean"/>
    213   </video>
    214 </div>
    215 
    216 <p>
    217   It seems to work, but still, something is off. We properly do all the collision detection, but the ball does not <strong>react</strong> in any way to the collisions. We need to update the ball's position and/or velocity whenever a collision occurs. This is the topic of the <a href="https://learnopengl.com/In-Practice/2D-Game/Collisions/Collision-resolution" target="_blank">next</a> chapter.
    218 </p>
    219        
    220 
    221     </div>
    222     
    223     <div id="hover">
    224         HI
    225     </div>
    226    <!-- 728x90/320x50 sticky footer -->
    227 <div id="waldo-tag-6196"></div>
    228 
    229    <div id="disqus_thread"></div>
    230 
    231     
    232 
    233 
    234 </div> <!-- container div -->
    235 
    236 
    237 </div> <!-- super container div -->
    238 </body>
    239 </html>