summaryrefslogtreecommitdiff
path: root/2d/rigidbody/rigidbody_2.html
blob: 53df7828830858e10fb84ad6a601c14b3d1e32e9 (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
<!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_2/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 #2: Rotational Forces</h1>
  <p>
    Now that we have linear forces acting upon the 2D objects in our scene, it is about time we incorporate rotational forces into our simulation. Please keep in mind that I do not go too into depth on why the rotational quantities and formulas are the way that they are. If you are looking for this information, I have linked to some great articles on physics (specifically Chris Hecker's articles!) on the home page.
  </p>
  <section>
    <h2>What are rotational forces?</h2>
    <p>
      Rotational forces help us to model how an object is rotating around its center of mass. The great part is that they have a lot in common with their linear counterparts: <b>torque</b> (&#x3C4;) is the rotational equivalent of linear force; <b>angular acceleration</b> (&#x3B1;) is the rotational equivalent of linear acceleration; <b>angular velocity</b> (&#969;) is the rotational equivalent of linear velocity; <b>moment of inertia</b> (I) is the rotational equivalent of center of mass; and the current <b>rotation</b> of an object is the equivalent of the position of the object. In two dimensions, all of the angular quantities can be defined using a single floating point number (in 3D, this gets a little more complicated).
    </p>
  </section>
  <section>
	<h2>The Data Structure</h2>
    <p>
      Rotational forces introduce three new quanities into our Rigid Body data structure:
      <ul>
        <li><b>Rotational Velocity</b> <i>(float)</i>: Much like linear velocity, this value defines the rate at which our object is currently rotating around its center of mass.</li>
        <li><b>Rotation</b> <i>(float)</i>: Much like position in the linear world, this value describes the current rotation of our object around its center of mass.</li>
        <li><b>Moment of inertia</b> <i>(float)</i>: This quanitity defined how much our object <i>wants to</i> rotate around its center of mass. A higher moment of inertia means an object is less likely to rotate, while a lower moment of a inertia means an object is more likely to rotate.</li>
      </ul>

      Adding these three new quanities to the Rigidbody struct from last time, we get someting that looks like this:

      <pre><code><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">float32</span> rotationalVelocity = 0.f;
    <span class="code_keyword">float32</span> rotation = 0.f;
    <span class="code_keyword">float32</span> momentOfInertia = 1.f;
    ...
}
</code></pre>
      Now, that's enough for the data side, let's see how we can input some forces into this data structure to make it move.
    </p>
  </section>
  <section>
    <h2>The Functions</h2>
    <p>
      When we inputted a force into our system in the first rigidbody example, we simply told the system "apply this force to the whole object over time." With the introduction of the rotational quantities into our model, we now say "apply this force <i>at this particualr point of the object</i> over time." This point is what we'll call the <b>point of application</b>. Our Impulse struct from last time will now look something like this:

      <pre><code><span class="code_keyword">struct</span> Impulse {
    <span class="code_keyword">Vector2</span> force = { 0, 0 };
    <span class="code_keyword">Vector2</span> pointOfApplication = { 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;
};
</code></pre>
      So what's the big deal about including this point of application? Well, from physics, we get the following formula:
      <br/>
      <div class="formula">
        <math class="formula">
          &#x3C4; = r x F
        </math>
      </div>
      
      In laymen's terms, this says that the torque is equal to the perpendicular of the force at <i>r</i>, which is the point of application. When you think about this in your head, it makes a lot of sense. For example, if you smack the top of a pencil from the top with your hand, it's not really going to rotate. However, if you smack the top of the pencil <i>from the side</i> with your hand, it is going to rotate a lot. This is because taking the cross product of the end of the pencil (i.e. the point of application) with the force of your hand (i.e. the force acting on the object) is much larger when <i>r</i> is perpendicular to <i>F</i>.

      <br/><br/>

      One thing to note is that, in 2D, we do not have the cross product, per se. The closest thing we can do is get the vector perpendicular to another vector using the following function:
      
      <pre><code><span class="code_keyword">Vector2</span> getPerp() {
    <span class="code_keyword">return</span> { y, -x };
}
</code></pre>
      <br/><br/>

      Now that we've calculate torque, we just need to get angular acceleration, which, when differentiated with respect to time, will yield the velocity and position. Angualr acceleration relates to torque according to this formula:
      <br/>
      <div class="formula">
        <math class="formula">
          &#x3C4; = I * &#x3B1;<br/>
          &#x3B1 = &#x3C4; / I
        </math>
      </div>

      The <i>I</i> in this case refers to the <b>moment of inertia</b> that I mentioned earlier. As you can tell, the larger the moment of inertia, the less like my object is going to be rotating. You can experience moment of inertia with the following example: Grab the middle of a pencil between your index and thumb fingers. Rotate it back and forth, and note how easy it is do so. Next, grab the end of the pencil and do the same thing. Note that it feels slightly more difficult to rotate the pencil now. This is because of moment of inertia! While you can calculate this quanitity (either manually or programatically), you will find the moment of inertia of many simple objects online. 
      
      <br/><br/>
      
      With all of this in mind, we're ready for the code that puts it all together!:

      <pre><code><span class="code_keyword">struct</span> Impulse {
    <span class="code_keyword">Vector2</span> force = { 0, 0 };
    <span class="code_keyword">Vector2</span> pointOfApplication = { 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;
};

<span class="code_keyword">const</span> <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">float32</span> rotationalVelocity = 0.f;
	<span class="code_keyword">float32</span> rotation = 0.f;
	<span class="code_keyword">float32</span> momentOfInertia = 1.f;

    <span class="code_keyword">void</span> reset() {
        numImpulses = 0;
        velocity = { 0, 0 };
        rotationalVelocity = 0.f;
        rotation = 0.f;
    }

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

        activeImpulses[numImpulses] = i;
        numImpulses++;
    }

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

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

        <span class="code_keyword">Vector2</span> force;
        <span class="code_keyword">float32</span> torque = 0.f;
        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;
                i.isDead = true;
            }
            
            <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;

            <span class="code_comment">// New! Increment the torque for each force</span>
            torque += i.pointOfApplication.getPerp().dot(forceToApply);

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

        <span class="code_comment">// New! Update the rotational velocity as well</span>
        <span class="code_keyword">float32</span> rotationalAcceleration = torque / momentOfInertia;
        rotationalVelocity += (rotationalAcceleration * deltaTimeSeconds);
        rotation += (rotationalVelocity * deltaTimeSeconds);

        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--;
            }
        }
    }
};
</code></pre>    </p>
  </section>
  <section>
	<h2>
	  Live Example
	</h2>
    <p>
      This demo is much like the one in the first rigidbody example, with the addition of torque.
    </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>
	
    <footer id="references">
      <h2>References</h2>
      <ul>
		<li><a href="https://en.wikipedia.org/wiki/List_of_moments_of_inertia">Moment of Inertia of Plate (which we use for a rectangle)</a></li>
      </ul>
    </footer>
  </section>
</article>
		</main>
	</body>
</html>