LearnOpenGL

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

Collision-resolution.html (17221B)


      1     <h1 id="content-title">Collision resolution</h1>
      2 <h1 id="content-url" style='display:none;'>In-Practice/2D-Game/Collisions/Collision-resolution</h1>
      3 <p>
      4   At the end of the last chapter we had a working collision detection system. However, the ball does not react in any way to the detected collisions; it moves straight through all the bricks. We want the ball to <em>bounce</em> of the collided bricks. This chapter discusses how we can accomplish this so called <def>collision resolution</def> within the AABB - circle collision detection logic.
      5 </p>
      6 
      7 <p>
      8   Whenever a collision occurs we want two things to happen: we want to reposition the ball so it is no longer inside the other object and second, we want to change the direction of the ball's velocity so it looks like it's bouncing of the object.
      9 </p>
     10 
     11 <h3>Collision repositioning</h3>
     12 <p>
     13   To position the ball object outside the collided AABB we have to figure out the distance the ball penetrated the bounding box. For this we'll revisit the diagram from the previous chapter:
     14 </p>
     15 
     16 <img src="/img/in-practice/breakout/collisions_aabb_circle_resolution.png" class="clean" alt="Collision resolution between circle and AABB"/>
     17   
     18 <p>
     19   Here the ball moved slightly into the AABB and a collision was detected. We now want to move the ball out of the shape so that it merely touches the AABB as if no collision occurred. To figure out how much we need to move the ball out of the AABB we need to retrieve the vector \(\color{brown}{\bar{R}}\), which is the level of penetration into the AABB. To get this vector \(\color{brown}{\bar{R}}\), we subtract \(\color{green}{\bar{V}}\) from the ball's radius. Vector \(\color{green}{\bar{V}}\) is the difference between closest point \(\color{red}{\bar{P}}\) and the ball's center \(\color{blue}{\bar{C}}\).
     20 </p>
     21   
     22 <p>
     23   Knowing \(\color{brown}{\bar{R}}\), we offset the ball's position by \(\color{brown}{\bar{R}}\) positioning it directly against the AABB; the ball is now properly positioned.
     24 </p>
     25   
     26 <h3>Collision direction</h3>
     27 <p>
     28    Next we need to figure out how to update the ball's velocity after a collision. For Breakout we use the following rules to change the ball's velocity: 
     29 </p>
     30   
     31   <ol>
     32     <li>If the ball collides with the right or left side of an AABB, its horizontal velocity (<code>x</code>) is reversed.</li>
     33     <li>If the ball collides with the bottom or top side of an AABB, its vertical velocity (<code>y</code>) is reversed.</li>
     34   </ol>
     35   
     36 <p>
     37   But how do we figure out the direction the ball hit the AABB? There are several approaches to this problem. One of them is that, instead of 1 AABB, we use 4 AABBs for each brick that we each position at one of its edges. This way we can determine which AABB and thus which edge was hit. However, a simpler approach exists with the help of the dot product.
     38 </p>
     39   
     40 <p>
     41   You probably still remember from the <a href="https://learnopengl.com/Getting-started/Transformations" target="_blank">transformations</a> chapter that the dot product gives us the angle between two normalized vectors. What if we were to define four vectors pointing north, south, west, and east, and calculate the dot product between them and a given vector? The resulting dot product between these four direction vectors and the given vector that is highest (dot product's maximum value is <code>1.0f</code> which represents a <code>0</code> degree angle) is then the direction of the vector. 
     42 </p>
     43   
     44 <p>
     45   This procedure looks as follows in code:
     46 </p>
     47   
     48 <pre><code>
     49 Direction VectorDirection(glm::vec2 target)
     50 {
     51     glm::vec2 compass[] = {
     52         glm::vec2(0.0f, 1.0f),	// up
     53         glm::vec2(1.0f, 0.0f),	// right
     54         glm::vec2(0.0f, -1.0f),	// down
     55         glm::vec2(-1.0f, 0.0f)	// left
     56     };
     57     float max = 0.0f;
     58     unsigned int best_match = -1;
     59     for (unsigned int i = 0; i &lt; 4; i++)
     60     {
     61         float dot_product = glm::dot(glm::normalize(target), compass[i]);
     62         if (dot_product &gt; max)
     63         {
     64             max = dot_product;
     65             best_match = i;
     66         }
     67     }
     68     return (Direction)best_match;
     69 }    
     70 </code></pre>
     71 
     72 <p>
     73   The function compares <var>target</var> to each of the direction vectors in the <var>compass</var> array. The compass vector <var>target</var> is closest to in angle, is the direction returned to the function caller. Here <var>Direction</var> is part of an enum defined in the game class's header file:
     74 </p>
     75   
     76 <pre><code>
     77 enum Direction {
     78 	UP,
     79 	RIGHT,
     80 	DOWN,
     81 	LEFT
     82 };    
     83 </code></pre>
     84   
     85 <p>
     86    Now that we know how to get vector \(\color{brown}{\bar{R}}\) and how to determine the direction the ball hit the AABB, we can start writing the collision resolution code.
     87 </p>
     88   
     89 <h3>AABB - Circle collision resolution</h3>
     90 <p>
     91     To calculate the required values for collision resolution we need a bit more information from the collision function(s) than just a <code>true</code> or <code>false</code>. We're now going to return a <def>tuple</def> of information that tells us if a collision occurred, what direction it occurred, and the difference vector \(\color{brown}{\bar{R}}\). You can find the <code>tuple</code> container in the <code>&lt;tuple&gt;</code> header.
     92 </p>
     93   
     94 <p>
     95   To keep the code slightly more organized we'll typedef the collision relevant data as <fun>Collision</fun>:
     96 </p>
     97   
     98 <pre><code>
     99 typedef std::tuple&lt;bool, Direction, glm::vec2&gt; Collision;    
    100 </code></pre>
    101   
    102 <p>
    103   Then we change the code of the <fun>CheckCollision</fun> function to not only return <code>true</code> or <code>false</code>, but also the direction and difference vector:
    104 </p>
    105   
    106 <pre><code>
    107 Collision CheckCollision(BallObject &one, GameObject &two) // AABB - AABB collision
    108 {
    109     [...]
    110     if (glm::length(difference) &lt;= one.Radius)
    111         return std::make_tuple(true, VectorDirection(difference), difference);
    112     else
    113         return std::make_tuple(false, UP, glm::vec2(0.0f, 0.0f));
    114 }
    115 </code></pre>
    116   
    117 <p>
    118   The game's <fun>DoCollision</fun> function now doesn't just check if  a collision occurred, but also acts appropriately whenever a collision did occur. The function now calculates the level of penetration (as shown in the diagram at the start of this tutorial) and adds or subtracts it from the ball's position based on the direction of the collision.
    119 </p>
    120   
    121 <pre><code>
    122 void Game::DoCollisions()
    123 {
    124     for (GameObject &box : this-&gt;Levels[this-&gt;Level].Bricks)
    125     {
    126         if (!box.Destroyed)
    127         {
    128             Collision collision = CheckCollision(*Ball, box);
    129             if (std::get&lt;0&gt;(collision)) // if collision is true
    130             {
    131                 // destroy block if not solid
    132                 if (!box.IsSolid)
    133                     box.Destroyed = true;
    134                 // collision resolution
    135                 Direction dir = std::get&lt;1&gt;(collision);
    136                 glm::vec2 diff_vector = std::get&lt;2&gt;(collision);
    137                 if (dir == LEFT || dir == RIGHT) // horizontal collision
    138                 {
    139                     Ball-&gt;Velocity.x = -Ball-&gt;Velocity.x; // reverse horizontal velocity
    140                     // relocate
    141                     float penetration = Ball-&gt;Radius - std::abs(diff_vector.x);
    142                     if (dir == LEFT)
    143                         Ball-&gt;Position.x += penetration; // move ball to right
    144                     else
    145                         Ball-&gt;Position.x -= penetration; // move ball to left;
    146                 }
    147                 else // vertical collision
    148                 {
    149                     Ball-&gt;Velocity.y = -Ball-&gt;Velocity.y; // reverse vertical velocity
    150                     // relocate
    151                     float penetration = Ball-&gt;Radius - std::abs(diff_vector.y);
    152                     if (dir == UP)
    153                         Ball-&gt;Position.y -= penetration; // move ball back up
    154                     else
    155                         Ball-&gt;Position.y += penetration; // move ball back down
    156                 }
    157             }
    158         }
    159     }
    160 }    
    161 </code></pre>
    162   
    163 <p>
    164   Don't get too scared by the function's complexity since it is basically a direct translation of the concepts introduced so far. First we check for a collision and if so, we destroy the block if it is non-solid. Then we obtain the collision direction <var>dir</var> and the vector \(\color{green}{\bar{V}}\) as <var>diff_vector</var> from the tuple and finally do the collision resolution.
    165 </p>
    166   
    167 <p>
    168   We first check if the collision direction is either horizontal or vertical and then reverse the velocity accordingly. If horizontal, we calculate the penetration value \(\color{brown}R\) from the <var>diff_vector</var>'s x component and either add or subtract this from the ball's position. The same applies to the vertical collisions, but this time we operate on the <code>y</code> component of all the vectors.
    169 </p>
    170   
    171 <p>
    172  Running your application should now give you working collision resolution, but it's probably difficult to really see its effect since the ball will bounce towards the bottom edge as soon as you hit a single block and be lost forever. We can fix this by also handling player paddle collisions. 
    173 </p>
    174   
    175 <h2>Player - ball collisions</h2>
    176 <p>
    177   Collisions between the ball and the player is handled slightly different from what we've previously discussed, since this time the ball's horizontal velocity should be updated based on how far it hit the paddle from its center. The further the ball hits the paddle from its center, the stronger its horizontal velocity change should be.
    178 </p>
    179   
    180 <pre><code>
    181 void Game::DoCollisions()
    182 {
    183     [...]
    184     Collision result = CheckCollision(*Ball, *Player);
    185     if (!Ball-&gt;Stuck && std::get&lt;0&gt;(result))
    186     {
    187         // check where it hit the board, and change velocity based on where it hit the board
    188         float centerBoard = Player-&gt;Position.x + Player-&gt;Size.x / 2.0f;
    189         float distance = (Ball-&gt;Position.x + Ball-&gt;Radius) - centerBoard;
    190         float percentage = distance / (Player-&gt;Size.x / 2.0f);
    191         // then move accordingly
    192         float strength = 2.0f;
    193         glm::vec2 oldVelocity = Ball-&gt;Velocity;
    194         Ball-&gt;Velocity.x = INITIAL_BALL_VELOCITY.x * percentage * strength; 
    195         Ball-&gt;Velocity.y = -Ball-&gt;Velocity.y;
    196         Ball-&gt;Velocity = glm::normalize(Ball-&gt;Velocity) * glm::length(oldVelocity);
    197     } 
    198 }
    199   </code></pre>
    200   
    201 <p>
    202   After we checked collisions between the ball and each brick, we'll check if the ball collided with the player paddle. If so (and the ball is not stuck to the paddle) we calculate the percentage of how far the ball's center is moved from the paddle's center compared to the half-extent of the paddle. The horizontal velocity of the ball is then updated based on the distance it hit the paddle from its center. In addition to updating the horizontal velocity, we also have to reverse the y velocity.
    203 </p>
    204   
    205 <p>
    206   Note that the old velocity is stored as <var>oldVelocity</var>. The reason for storing the old velocity is that we update the horizontal velocity of the ball's velocity vector while keeping its <code>y</code> velocity constant. This would mean that the length of the vector constantly changes, which has the effect that the ball's velocity vector is much larger (and thus stronger) if the ball hit the edge of the paddle compared to if the ball would hit the center of the paddle. For this reason, the new velocity vector is normalized and multiplied by the length of the old velocity vector. This way, the velocity of the ball is always consistent, regardless of where it hits the paddle.
    207 </p>
    208   
    209 <h3>Sticky paddle</h3>
    210 <p>
    211   You may or may not have noticed it when you ran the code, but there is still a large issue with the  player and ball collision resolution. The following shows what may happen:
    212 </p>
    213   
    214 <div class="video paused" onclick="ClickVideo(this)">
    215   <video width="600" height="450" loop>
    216     <source src="/video/in-practice/breakout/collisions_sticky_paddle.mp4" type="video/mp4" />
    217     <img src="/img/in-practice/breakout/collisions_sticky_paddle.png" class="clean"/>
    218   </video>
    219 </div>
    220 
    221 <p>
    222   This issue is called the <def>sticky paddle</def> issue. This happens, because the player paddle moves with a high velocity towards the ball with the ball's center ending up inside the player paddle. Since we did not account for the case where the ball's center is inside an AABB, the game tries to continuously react to all the collisions. Once it finally breaks free, it will have reversed its <code>y</code> velocity so much that it's unsure whether to go up or down after breaking free.
    223 </p>
    224   
    225 <p>
    226   We can easily fix this behavior by introducing a small hack made possible by the fact that the we can always assume we have a collision at the top of the paddle. Instead of reversing the <code>y</code> velocity, we simply always return a positive <code>y</code> direction so whenever it does get stuck, it will immediately break free.
    227 </p>
    228   
    229 <pre><code>
    230  //Ball->Velocity.y = -Ball->Velocity.y;
    231 Ball->Velocity.y = -1.0f * abs(Ball->Velocity.y);  
    232 </code></pre>
    233 
    234 <p>
    235   If you try hard enough the effect is still noticeable, but I personally find it an acceptable trade-off. 
    236 </p>
    237   
    238 <h3>The bottom edge</h3>
    239 <p>
    240   The only thing that is still missing from the classic Breakout recipe is some loss condition that resets the level and the player. Within the game class's <fun>Update</fun> function we want to check if the ball reached the bottom edge, and if so, reset the game.
    241 </p>
    242   
    243 <pre><code>
    244 void Game::Update(float dt)
    245 {
    246     [...]
    247     if (Ball->Position.y >= this->Height) // did ball reach bottom edge?
    248     {
    249         this->ResetLevel();
    250         this->ResetPlayer();
    251     }
    252 }  
    253 </code></pre>
    254   
    255 <p>
    256   The <fun>ResetLevel</fun> and <fun>ResetPlayer</fun> functions re-load the level and reset the objects' values to their original starting values. The game should now look a bit like this:
    257 </p>
    258   
    259 <div class="video paused" onclick="ClickVideo(this)">
    260   <video width="600" height="450" loop>
    261     <source src="/video/in-practice/breakout/collisions_complete.mp4" type="video/mp4" />
    262   </video> 
    263 </div>
    264   
    265 <p>
    266   And there you have it, we just finished creating a clone of the classical Breakout game with similar mechanics. You can find the game class' source code here: <a href="/code_viewer_gh.php?code=src/7.in_practice/3.2d_game/0.full_source/progress/5.game.h" target="_blank">header</a>, <a href="/code_viewer_gh.php?code=src/7.in_practice/3.2d_game/0.full_source/progress/5.game.cpp" target="_blank">code</a>.
    267   </p>
    268   
    269 <h2>A few notes</h2>
    270 <p>
    271   Collision detection is a difficult topic of video game development and possibly its most challenging. Most collision detection and resolution schemes are combined with physics engines as found in most modern-day games. The collision scheme we used for the Breakout game is a very simple scheme and one specialized specifically for this type of game. 
    272   </p>
    273   
    274 <p>
    275  It should be stressed that this type of collision detection and resolution is not perfect. It calculates possible collisions only per frame and only for the positions exactly as they are at that timestep; this means that if an object would have such a velocity that it would pass over another object within a single frame, it would look like it never collided with this object. So if there are framedrops, or you reach high enough velocities, this collision detection scheme will not hold.  
    276 </p>
    277   
    278 <p>
    279     Several of the issues that can still occur:
    280 </p>
    281   
    282 <ul>
    283 	<li>If the ball goes too fast, it may skip over an object entirely within a single frame, not detecting any collisions.</li>
    284   <li>If the ball hits more than one object within a single frame, it will have detected two collisions and reversed its velocity twice; not affecting its original velocity.</li>
    285   <li>Hitting a corner of a brick could reverse the ball's velocity in the wrong direction since the distance it travels in a single frame could decide the difference between <fun>VectorDirection</fun> returning a vertical or horizontal direction.</li>
    286 </ul>
    287   
    288 <p>
    289   These chapters are however aimed to teach the readers the basics of several aspects of graphics and game-development. For this reason, this collision scheme serves its purpose; its understandable and works quite well in normal scenarios. Just keep in mind that there exist better (more complicated) collision schemes that work well in almost all scenarios (including movable objects) like the <def>separating axis theorem</def>.
    290 </p>
    291   
    292 <p>
    293   Thankfully, there exist large, practical, and often quite efficient physics engines (with timestep-independent collision schemes) for use in your own games. If you wish to delve further into such systems or need  more advanced physics and have trouble figuring out the mathematics, <a href="http://box2d.org/" target="_blank">Box2D</a> is a perfect 2D physics library for implementing physics and collision detection in your applications.
    294 </p>
    295        
    296 
    297     </div>
    298     
    299     <div id="hover">
    300         HI
    301     </div>
    302    <!-- 728x90/320x50 sticky footer -->
    303 <div id="waldo-tag-6196"></div>
    304 
    305    <div id="disqus_thread"></div>
    306 
    307     
    308 
    309 
    310 </div> <!-- container div -->
    311 
    312 
    313 </div> <!-- super container div -->
    314 </body>
    315 </html>