summaryrefslogtreecommitdiff
path: root/2d/rigidbody/rigidbody_1.html
blob: 8e78972c1b80c3e045130c11b31a468e166ab664 (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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="utf-8">
		<link rel="stylesheet" href="/index.css">
		<title>Physics for Games</title>
		<link rel="shortcut icon" href="favicon/favicon.ico" type="image/x-icon">
		<meta name="description" content="A place to learn all about real-time physics simulations through descriptions, code snippets, and example programs all written in C++ and OpenGL.">
		<meta name="og:description" content="A place to learn all about real-time physics simulations through descriptions, code snippets, and example programs all written in C++ and OpenGL.">
	</head>
	<body>
		<header>
			<h1><a title="physicsforgames.com" href="/">Physics for Games</a></h1>
		</header>
		<main>
		<nav>
		<ul class="outer-tree">
			<li><a href="/">Introduction</a></li>
			<li>
				<span>&#127936;<span>2D</span></span>
				<ul class="inner-tree">
					<li><label>Rigidbody</label></li>
					<li><a title="/2d/rigidbody/rigidbody_1.html" href="/2d/rigidbody/rigidbody_1.html">Linear Forces</a></li>
					<li><a title="/2d/rigidbody/rigidbody_2.html" href="/2d/rigidbody/rigidbody_2.html">Rotational Forces</a></li>
					<li><a title="/2d/rigidbody/rigidbody_3.html" href="/2d/rigidbody/rigidbody_3.html">Collisions</a></li>
					<li><label>Collisions</label></li>
					<li><a title="/2d/_collisions/rectangle_line.html" href="/2d/_collisions/rectangle_line.html">Rectangle-Line</a></li>
					<li><a title="/2d/_collisions/rectangle_rectangle.html" href="/2d/_collisions/rectangle_rectangle.html">Rectangle-Rectangle</a></li>
					<li><a title="/2d/_collisions/polygon_polygon.html" href="/2d/_collisions/polygon_polygon.html">Separating Axis Theorem</a></li>
				</ul>
			</li>
			<li>
				<span>&#127776;<span>3D</span></span>
				<ul class="inner-tree">
					<li><label>Rigidbody</label></li>
					<li><a title="/3d/rigidbody.html" href="/3d/rigidbody.html">Rigidbody in 3D</a></li>
				</ul>
			</li>
			<li>
				<span>&#128295;<span>WebAssembly</span></span>
				<ul class="inner-tree">
					<li><a title="/intro/intro.html" href="/intro/intro.html">Introduction</a></li>
				</ul>
			</li>
			<li>
				<span>&#128712;<span>About</span></span>
				<ul class="inner-tree">
					<li><a title="/roadmap.html" href="/roadmap.html">Roadmap</a></li>
				</ul>
			</li>
		</ul>
		</nav>
<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 Kinematics 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.

      <pre><code><span class="code_keyword">struct</span> Rigidbody {
    <span class="code_keyword">Vector2</span> force = { 0, 0 };
    <span class="code_keyword">Vector2</span> velocity = { 0, 0 };
    <span class="code_keyword">Vector2</span> position = { 0, 0 };
    <span class="code_keyword">float32</span> mass = 1.f;
};
</code></pre>
      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 Dynamics 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.

      <pre><code><span class="code_keyword">struct</span> Rigidbody {
    <span class="code_keyword">Vector2</span> force = { 0, 0 };
    <span class="code_keyword">Vector2</span> velocity = { 0, 0 };
    <span class="code_keyword">Vector2</span> position = { 0, 0 };
    <span class="code_keyword">float32</span> mass = 1.f;

    <span class="code_keyword">void</span> update(float32 deltaTimeSeconds) {
        applyGravity(deltaTimeSeconds);
        
        <span class="code_keyword">Vector2</span> acceleration = force / mass;
        velocity += (acceleration * deltaTimeSeconds);
        position += (velocity * deltaTimeSeconds);
        force = <span class="code_keyword">Vector2</span> { 0.f, 0.f };
    }

    <span class="code_keyword">void</span> applyGravity(float32 deltaTimeSeconds) {
        velocity += (Vector2 { 0.f, -9.8.f } * deltaTimeSeconds);
    }

    <span class="code_keyword">void</span> applyForce(Vector2 f) {
        force += f;
    }
};
</code></pre>
      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>:

      <pre><code><span class="code_keyword">struct</span> Impulse {
    <span class="code_keyword">Vector2</span> force = { 0, 0 };
    <span class="code_keyword">float32</span> timeOfApplicationSeconds = 0.25f;
    <span class="code_keyword">float32</span> timeAppliedSeconds = 0.f;
    <span class="code_keyword">bool</span> isDead = false;
};

const <span class="code_keyword">int32</span> NUM_IMPULSES = 4;

<span class="code_keyword">struct</span> Rigidbody {
    <span class="code_keyword">int32</span> numImpulses = 0;
    Impulse activeImpulses[NUM_IMPULSES];
    <span class="code_keyword">Vector2</span> velocity = { 0, 0 };
    <span class="code_keyword">Vector2</span> position = { 0, 0 };
    <span class="code_keyword">float32</span> mass = 1.f;

    <span class="code_keyword">void</span> update(float32 deltaTimeSeconds) {
        applyGravity(deltaTimeSeconds);

        <span class="code_keyword">Vector2</span> force;
        for (int32 idx = 0; idx < numImpulses; idx++) {
            Impulse& i = activeImpulses[idx];

            <span class="code_keyword">float32</span> nextTimeAppliedSeconds = i.timeAppliedSeconds + deltaTimeSeconds;
            if (nextTimeAppliedSeconds >= i.timeOfApplicationSeconds) {
                nextTimeAppliedSeconds = i.timeOfApplicationSeconds; <span class="code_comment">// Do the remainder of the time</span>
                i.isDead = true;
            }
            
            <span class="code_comment">// We apply the force spread out over timeOfApplicationSeconds, so we need</span>
            <span class="code_comment">// to calculate the fractional amount of force that was applied in this frame.</span>
            <span class="code_keyword">float32</span> impulseDtSeconds = nextTimeAppliedSeconds - i.timeAppliedSeconds;
            <span class="code_keyword">Vector2</span> forceToApply = i.force * (impulseDtSeconds / i.timeOfApplicationSeconds);
            force += forceToApply * impulseDtSeconds;
            i.timeAppliedSeconds = nextTimeAppliedSeconds;
        }

        <span class="code_keyword">Vector2</span> acceleration = force / mass;
        velocity += (acceleration * deltaTimeSeconds);
        position += (velocity * deltaTimeSeconds);

        <span class="code_comment">// Cleanup any impulses that have expired in the mean time</span>
        for (int32 idx = 0; idx < numImpulses; idx++) {
            if (activeImpulses[idx].isDead) {
                for (int j = idx + 1; j < numImpulses; j++) {
                    activeImpulses[j - 1] = activeImpulses[j];
                }

                idx = idx - 1;
                numImpulses--;
            }
        }
    }

    <span class="code_keyword">void</span> applyGravity(float32 deltaTimeSeconds) {
        velocity += (Vector2 { 0.f, -9.8f } * deltaTimeSeconds);
    }

    <span class="code_keyword">void</span> applyImpulse(Impulse i) {
        if (numImpulses > NUM_IMPULSES) {
            printf("Unable to apply impulse. Buffer full.\n");
            return;
        }

        activeImpulses[numImpulses] = i;
        numImpulses++;
    }
};
</code></pre>
      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>
		</main>
	</body>
</html>