summaryrefslogtreecommitdiff
path: root/2d/rigidbody/rigidbody_1.html.content
blob: 567ca980dfaab08f0ffa5ad6e00d26269152ca3f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
<script src="./rigidbody_1/dist/output.js"></script>
<script>
  window.onload = function() {
      var lPlayElement = document.getElementById('gl_canvas_play'),
          lStopElement = document.getElementById('gl_canvas_stop');
      lPlayElement.addEventListener('click', function() {
          lPlayElement.style.display = 'none';
          lStopElement.style.display = 'block';
      });
      lStopElement.addEventListener('click', function() {
          lStopElement.style.display = 'none';
          lPlayElement.style.display = 'block';
      });
  }
  
</script>
<article>
  <h1>Rigidbody #1: Linear Forces</h1>
  <section>
	<p>
      In this first installment of my 2D rigidbody tutorial, we are going to explore linear forces and how we can begin to simulate them in real time on a computer. As you'll come to see, 2D forces are quite easy to understand and implement if you have some basic knowledge of 2D maths. On top of that, they really add a lot of life into what would otherwise be a static 2D scene.
	</p>
  </section>
  <section>
    <h2>What do we mean by Rigid Body Physics?</h2>
    <p>
      When we say that the objects in our scene have "rigidbodies", we are assuming the following things:
      <ul>
        <li>The object can never be disformed by the physics system. This means that, when collisions happen, objects will always bounce off of one another. There will never be an instance where one object squishes or puts a hole into another object. No penetration is allowed.</li>
        <li>Mass is uniformly distributed throughout the object. This assumption allows us to think of the rigidbody as a single point, which represents the center of mass of our object. You will notice later in this tutorial that the rigidbody formulas work regardless of the shape and size of the object as a result of this assumption.</li>
      </ul>
      With that knowledge in mind, let's start digging into some implementation.
    </p>
  </section>
  <section>
    <h2>A Tale of Two Sub-Fields</h2>
    <p>
      When discussing a rigidy body physics system, we're interested in two sub-fields of physics, namely <b>dynamics</b> and <b>kinematics</b>. Although I'm far as can be from being an expert in either of these fields, I will explain - from a programmer's perspective - what they mean to me:

      <ul>
        <li>
          <b>Kinematics</b> is the study of how an object's movement changes over time. These are the classic position, velocity, and acceleration equations that you're most likely familiar with from high school or college physics. Kinematics doesn't care about <i>how</i> a system entered into the state that it is in, but rather that the system <i>is</i> in that state.
        </li>
        <li>
          <b>Dynamics</b> is the study of whats <i>causes</i> kinematic movement. These are the classic force and momentum equations that you may already be familiar with as well. Whereas kinematics only worries itself with the current state of the system, dynamics wants to know <i>how</i> the system entered the state that it is currently in.
        </li>
      </ul>

      Although the distinction between these two subfields may seem inconsequential, it impacts the conceptual way in which we might begin to setup our 2D rigidbody simulation: <i>the kinematic variables are the data that we act upon, while the dynamics variables are the data that we apply</i>. 
    </p>

  </section>
  <section>
    <h2>The Data Structure</h2>
    <p>
      Now that we have an understanding of these two fundamental fields of physics, we can begin setting up our rigidbody data structure.

      #SNIPPET rigidbody_1/snippet1.cpp

      As you can see, the base data structure exactly mirrors what we already know from 2D newtonian physics. Every frame, we will have some <i>force</i> applied to our rigidbody. We will use that <i>force</i> to get <i>accleration</i>, which, when differentied with respect to time, yields velocity and, ultimately, the new position of our rigidbody. For all of this to work, of course, we need a constant <i>mass</i> for this object.
    </p>
  </section>
  <section>
    <h2>The Functions</h2>
    <p>
      Now, let's put that Rigidbody data structure to work! As I mentioned earlier, you can think of dynamics as the <i>input</i> to the system. What we're going to do now is add a way apply some sort of force to our rigidbody instantaneously.

      #SNIPPET rigidbody_1/snippet2.cpp

      We have three new functions here:
      <ul>
        <li><b>update</b>: This function will run every single frame during our simulation. In it, we use the total force being applied on the object at this time (found by reordering the classic equation <i>F = ma</i>). From there, we differentiate once with respect to time to get the velocity, and again to get the position. Finally, we reset the total force to zero so that we can start fresh on the next frame.</li>
        <li><b>applyGravity</b>: We all know that gravity is a constant 9.8 m/s<sup>2</sup>, so we can simply add that to the velocity every single frame. (Note that the gravity in your game may not 9.8; don't be afraid to mess around with this number).</li>
        <li><b>applyForce</b>: This function provies a way for external forces to affect our rigidbody directly.</li>
      </ul>

      Voila! We have everything we need to start applying forces. But wait! There is one more thing to consider...
    </p>
  </section>
  <section>
    <h2>Impulses & Frame-Rate Independence</h2>
    <p>
      Although it might be good enough for your use case, allow me to explain why the previous approach is neither realistic nor reliable:<br/><br/>

      When a force is applied in the real world, it doesn't just get applied for a single moment (i.e. frame) in time: it gets applied <i>over</i> time, or for a given <i>duration</i> of time. At the moment, our current implementation fails to account for this. forces are applied for a given frame, and then forgotten about.<br/><br/>

      Our current approach has another problem too: the applied force is <b>not</b> frame-rate independent. If you were to apply a force of 50N in the Y direction right now, slower computers would experience larger resultant velocities because their <i>deltaTimeSeconds</i> would be much larger. This is generally something that you'd want to avoid in most applications.<br/><br/>

      One potential fix for this is to use <b>impulses</b>:

      #SNIPPET rigidbody_1/snippet3.cpp

      While a bit more verbose than our previous example, this approach has more reliable behavior. Forces are no longer treated as single moments in time, but rather "forces applied <i>over</i> time". Because we ensure that the force is applied over time, we guarantee that all users see the same amount of force applied, regardless of frame-rate.<br/><br/>

      For anyone interested, the algorithm for using impulses is as follows:
      <ul>
        <li>Get all impulses acting on the rigidbody at this moment</li>
        <li>For each impulse, find out how much time is remaining. Apply the remaining force, and mark those that have expired as dead</li>
        <li>Calculate the acceleration, velocity, and position as before</li>
        <li>Remove any dead impulses from the list</li>
      </ul>

      Keep in mind that you can still have what amounts to an "instant" force being applied if you set the duration of the impulse to be very small. Feel free to look at the example program below (and browse/download the code) if you want to see it in action.
    </p>
  </section>
  <section>
	<h2>
	  Live Example
	</h2>
    <p>
      Click 'Play' on the WebAssembly demo below to see a square bouncing around the screen. When you drag the pointer through the square, we will apply an impulse equivalent to how fast you were moving your mouse in the direction that you were moving it.
    </p>
    <div class="opengl_canvas_container">
      <canvas id="gl_canvas" width="800" height="600"></canvas>
      <button id="gl_canvas_play" class="play_button">
        Play
      </button>
      <button id="gl_canvas_stop" class="stop_button">
        Stop
      </button>
    </div>
  </section>
  <footer id="references">
    <h2>References</h2>
    <ul>
      <li><a href='https://www.thoughtco.com/impulse-2698956'>Impulse Information</a></li>
    </ul>
  </footer>
</article>