mirror of
https://github.com/nature-of-code/noc-book-2
synced 2024-11-17 07:49:05 +01:00
1044 lines
No EOL
91 KiB
HTML
1044 lines
No EOL
91 KiB
HTML
<section data-type="chapter">
|
||
<h1 id="chapter-3-oscillation">Chapter 3. Oscillation</h1>
|
||
<blockquote data-type="epigraph">
|
||
<p>“Trigonometry is a sine of the times.”</p>
|
||
<p>— Anonymous</p>
|
||
</blockquote>
|
||
<p>In Chapters 1 and 2, I carefully worked out an object-oriented structure to animate a shape in a p5.js canvas, using the concept of a vector to represent position, velocity, and acceleration driven by forces in the environment. I could move straight from here into topics such as particle systems, steering forces, group behaviors, and more. However, doing so would mean skipping a fundamental aspect of motion in the natural world: <strong>oscillation</strong>, or the back-and-forth movement of an object around a central point or position. In order to model oscillation, you’ll need to understand a little bit about trigonometry.</p>
|
||
<p><strong>Trigonometry</strong> is the mathematics of triangles, specifically right triangles. Learning some trig will give you new tools to generate patterns and create new motion behaviors in a p5.js sketch. You’ll learn to harness angular velocity and acceleration to spin objects as they move. You’ll be able to use the sine and cosine functions to model nice ease-in, ease-out wave patterns. You’ll also learn to calculate the more complex forces at play in situations that involve angles, such as a pendulum swinging or a box sliding down an incline.</p>
|
||
<p>I’ll start the chapter with the basics of working with angles in p5.js, then cover several aspects of trigonometry. In the end, I’ll connect trigonometry with what you learned about forces in Chapter 2. What I cover here will pave the way for more sophisticated examples that require trig later in this book.</p>
|
||
<h2 id="angles">Angles</h2>
|
||
<p>Before going any further, I need to make sure you understand what it means to be an <strong>angle</strong> in p5.js. If you have experience with p5.js, you’ve undoubtedly encountered this issue while using the <code>rotate()</code> function to rotate and spin objects.</p>
|
||
<p>You’re most likely to be familiar with the concept of an angle as measured in <strong>degrees</strong> (see Figure 3.1). A full rotation goes from 0 to 360 degrees, and 90 degrees (a right angle) is 1/4th of 360, shown in Figure 3.1 as two perpendicular lines.</p>
|
||
<figure>
|
||
<img src="images/03_oscillation/03_oscillation_1.png" alt="Figure 3.1 Angles measured in degrees">
|
||
<figcaption>Figure 3.1 Angles measured in degrees</figcaption>
|
||
</figure>
|
||
<figure class="half-width-right">
|
||
<img src="images/03_oscillation/03_oscillation_2.png" alt="Figure 3.2: A square rotated by 45 degrees">
|
||
<figcaption>Figure 3.2: A square rotated by 45 degrees</figcaption>
|
||
</figure>
|
||
<p>Angles are commonly used in computer graphics to specify a rotation for a shape. For example, the square in Figure 3.2 is rotated 45 degrees around its center.</p>
|
||
<figure class="half-width-right">
|
||
<img src="images/03_oscillation/03_oscillation_3.png" alt="Figure 3.3: The arc length for an angle of 1 radian is equal to the radius.">
|
||
<figcaption>Figure 3.3: The arc length for an angle of 1 radian is equal to the radius.</figcaption>
|
||
</figure>
|
||
<p>The catch is that, by default, p5.js measures angles not in degrees but in <strong>radians</strong>. This alternative unit of measurement is defined by the ratio of the length of the arc of a circle (a segment of the circle’s circumference) to the radius of that circle. One radian is the angle at which that ratio equals one (see Figure 3.3). A full circle (360 degrees) is equivalent to <span data-type="equation">2\pi</span> radians, 180 degrees is equivalent to <span data-type="equation">\pi</span> radians, and 90 degrees is equivalent to <span data-type="equation">\pi/2</span> radians.</p>
|
||
<div data-type="note">
|
||
<h3 id="what-is-pi">What is PI?</h3>
|
||
<p>The mathematical constant pi (or the Greek letter <span data-type="equation">\pi</span>) is a real number defined as the ratio of a circle’s circumference (the distance around the outside of the circle) to its diameter (a straight line that passes through the circle’s center). It’s equal to approximately 3.14159 and can be accessed in p5.js with the built-in <code>PI</code> variable.</p>
|
||
</div>
|
||
<p>The formula to convert from degrees to radians is:</p>
|
||
<div data-type="equation">\text{radians} = {2\pi \times \text{degrees} \over 360}</div>
|
||
<p>Thankfully, if you prefer to think of angles in degrees, you can call <code>angleMode(DEGREES)</code>, or you can use the convenience function <code>radians()</code> to convert values from degrees to radians. The constants<code>PI</code> , <code>TWO_PI</code> , and <code>HALF_PI</code>are also available (equivalent to 180, 360, and 90 degrees , respectively). For example, here are two ways in p5.js to rotate a shape by 60 degrees:</p>
|
||
<pre class="codesplit" data-code-language="javascript">let angle = 60;
|
||
rotate(radians(angle));
|
||
|
||
angleMode(DEGREES);
|
||
rotate(angle);</pre>
|
||
<p>While degrees can be useful, for the purposes of this book, I’ll be working with radians because they’re the standard unit of measurement across many programming languages and graphics environments. If they're new to you, this is a good opportunity to practice! Additionally, if you aren’t familiar with how rotation is implemented in p5.js, I recommend watching <a href="https://thecodingtrain.com/tracks/transformations-in-p5">my Coding Train video series on transformations in p5.js</a>.</p>
|
||
<div data-type="exercise">
|
||
<h3 id="exercise-31">Exercise 3.1</h3>
|
||
<p>Rotate a baton-like object around its center using <code>translate()</code> and <code>rotate()</code>.</p>
|
||
<figure>
|
||
<div data-type="embed" data-p5-editor="https://editor.p5js.org/natureofcode/sketches/KGSjouINj" data-example-path="examples/03_oscillation/exercise_3_1_baton"><img src="examples/03_oscillation/exercise_3_1_baton/screenshot.png"></div>
|
||
<figcaption></figcaption>
|
||
</figure>
|
||
</div>
|
||
<h2 id="angular-motion">Angular Motion</h2>
|
||
<p>Another term for rotation is <strong>angular motion</strong>—that is, motion about an angle. Just as linear motion can be described in terms of velocity—the rate at which an object’s position changes over time—angular motion can be described in terms of <strong>angular velocity</strong>—that rate at which an object’s angle changes over time. By extension, <strong>angular acceleration</strong> describes changes in an object’s angular velocity.</p>
|
||
<p>Luckily, you already have all the math you need to understand angular motion. Remember the stuff I dedicated almost all of Chapters 1 and 2 to explaining?</p>
|
||
<div data-type="equation">\overrightarrow{\text{velocity}} = \overrightarrow{\text{velocity}} + \overrightarrow{\text{acceleration}}</div>
|
||
<div data-type="equation">\overrightarrow{\text{position}} = \overrightarrow{\text{position}} + \overrightarrow{\text{velocity}}</div>
|
||
<p>You can apply exactly the same logic to a rotating object:</p>
|
||
<div data-type="equation">\text{angular velocity} = \text{angular velocity} + \text{angular~acceleration}</div>
|
||
<div data-type="equation">\text{angle} = \text{angle} + \text{angular velocity}</div>
|
||
<p>In fact, these angular motion formulas are simpler than their linear motion equivalents because an angle is a <em>scalar</em> quantity (a single number), not a vector!</p>
|
||
<p>(Note: In most contexts, these formulas include a multiplication by the change in time, referred to as “delta-time”. I’m assuming a delta-time of 1 that corresponds to one frame of animation in p5.js. Also, the angular values are only treated as scalars because I am focusing on two-dimensional space, where there is one axis of rotation!)</p>
|
||
<p>Using the answer from Exercise 3.1, let’s say you wanted to rotate a baton in p5.js by some angle. Originally, the code might have read:</p>
|
||
<pre class="codesplit" data-code-language="javascript">translate(width / 2, height / 2);
|
||
rotate(angle);
|
||
line(-60, 0, 60, 0);
|
||
circle(60, 0, 16);
|
||
circle(-60, 0, 16, 16);
|
||
|
||
angle = angle + 0.1;</pre>
|
||
<p>Adding in the principles of angular motion, I can instead write the following example (the solution to Exercise 3.1).</p>
|
||
<div data-type="example">
|
||
<h3 id="example-31-angular-motion-using-rotate">Example 3.1: Angular Motion Using rotate()</h3>
|
||
<figure>
|
||
<div data-type="embed" data-p5-editor="https://editor.p5js.org/natureofcode/sketches/EFCfyH88E" data-example-path="examples/03_oscillation/example_3_1_angular_motion_using_rotate"><img src="examples/03_oscillation/example_3_1_angular_motion_using_rotate/screenshot.png"></div>
|
||
<figcaption></figcaption>
|
||
</figure>
|
||
</div>
|
||
<pre class="codesplit" data-code-language="javascript">// Position
|
||
let angle = 0;
|
||
// Velocity
|
||
let angleVelocity = 0;
|
||
//{!1} Acceleration
|
||
let angleAcceleration = 0.0001;
|
||
|
||
function setup() {
|
||
createCanvas(640, 240);
|
||
}
|
||
|
||
function draw() {
|
||
background(255);
|
||
|
||
translate(width / 2, height / 2);
|
||
rotate(angle);
|
||
|
||
stroke(0);
|
||
fill(127);
|
||
|
||
line(-60, 0, 60, 0);
|
||
circle(60, 0, 16);
|
||
circle(-60, 0, 16);
|
||
|
||
// Angular equivalent of velocity.add(acceleration);
|
||
angleVelocity += angleAcceleration;
|
||
//{!1} Angular equivalent of position.add(velocity);
|
||
angle += angleVelocity;
|
||
}</pre>
|
||
<p>Instead of incrementing <code>angle</code> by a fixed amount to steadily rotate the baton, every frame I add <code>angleAcceleration</code> to <code>angleVelocity</code>, then add <code>angleVelocity</code> to <code>angle</code>. As a result, the baton starts with no rotation, and then spins faster and faster as the angular velocity accelerates.</p>
|
||
<div data-type="exercise">
|
||
<h3 id="exercise-32">Exercise 3.2</h3>
|
||
<p>Add an interaction to the spinning baton. How can you control the acceleration with the mouse? Can you introduce the idea of drag, decreasing the angular velocity over time so the baton eventually comes to rest?</p>
|
||
</div>
|
||
<p>The logical next step is to incorporate this idea of angular motion into the <code>Mover</code> class. First, I need to add some variables to the class’s constructor.</p>
|
||
<pre class="codesplit" data-code-language="javascript">class Mover {
|
||
constructor(){
|
||
this.position = createVector();
|
||
this.velocity = createVector();
|
||
this.acceleration = createVector();
|
||
this.mass = 1.0;
|
||
|
||
//{!3} Variables for angular motion
|
||
this.angle = 0;
|
||
this.angleVelocity = 0;
|
||
this.angleAcceleration = 0;
|
||
}
|
||
|
||
}</pre>
|
||
<p>Then, in <code>update()</code>, the mover’s position and angle are updated according to the algorithm I just demonstrated.</p>
|
||
<pre class="codesplit" data-code-language="javascript">update() {
|
||
//{!2} Regular old-fashioned motion
|
||
this.velocity.add(this.acceleration);
|
||
this.position.add(this.velocity);
|
||
|
||
//{!2} Newfangled angular motion
|
||
this.angleVelocity += this.angleAcceleration;
|
||
this.angle += this.angleVelocity;
|
||
|
||
this.acceleration.mult(0);
|
||
}</pre>
|
||
<p>Of course, for any of this to matter, I also need to rotate the object when drawing it in the <code>show()</code> method. (I’ll add a line from the center to the edge of the circle so that rotation is visible. You could also draw the object as a shape other than a circle.)</p>
|
||
<pre class="codesplit" data-code-language="javascript">show() {
|
||
stroke(0);
|
||
fill(175, 200);
|
||
|
||
//{!1} push() saves the current state so the rotation of this shape doesn’t affect the rest of the world
|
||
push();
|
||
// Set the origin at the shape’s position.
|
||
translate(this.position.x, this.position.y);
|
||
//{!1} Rotate by the angle.
|
||
rotate(this.angle);
|
||
circle(0, 0, this.radius * 2);
|
||
line(0, 0, this.radius, 0);
|
||
//{!1} pop() restores the previous state after rotation is complete
|
||
pop();
|
||
}</pre>
|
||
<p>At this point, if you were to actually go ahead and create a <code>Mover</code> object, you wouldn’t see it behave any differently. This is because the angular acceleration is initialized to zero (<code>this.angleAcceleration = 0;</code>) . For the object to rotate, it needs a non-zero acceleration! Certainly, one option is to hard-code a number in the constructor:</p>
|
||
<pre class="codesplit" data-code-language="javascript"> this.angleAcceleration = 0.01;</pre>
|
||
<p>You can produce a more interesting result, however, by dynamically assigning an angular acceleration in the <code>update()</code> method according to forces in the environment. This could be my cue to start researching the physics of angular acceleration based on the concepts of <a href="http://en.wikipedia.org/wiki/Torque">torque</a> and <a href="http://en.wikipedia.org/wiki/Moment_of_inertia">moment of inertia</a>, but at this state, that level of simulation would be a bit of a rabbit hole. (I’ll cover more about modeling angular acceleration with a pendulum later in this chapter, as well as look at how other physics libraries realistically models rotational motion in Chapter 6.) Instead, a quick and dirty solution that yields creative results will suffice. A reasonable approach is to calculate angular acceleration as a function of the object's “linear acceleration,” its rate of change of velocity along a path vector, as opposed to its rotation. Here’s an example:</p>
|
||
<pre class="codesplit" data-code-language="javascript"> // Using the x component of the object's linear acceleration to calculate angular acceleration
|
||
this.angleAcceleration = this.acceleration.x;</pre>
|
||
<p>Yes, this is arbitrary, but it does do <em>something</em>. If the object is accelerating to the right, its angular rotation accelerates in a clockwise direction; acceleration to the left results in a counterclockwise rotation. Of course, it’s important to think about scale in this case. The value of the acceleration vector’s <code>x</code> component might be too large, causing the object to spin in a way that looks ridiculous or unrealistic. You might even notice a visual illusion called the “wagon wheel effect,” where an object appears to be rotating slower or even in the opposite direction due to the large changes between each frame of animation.</p>
|
||
<p>Dividing the <code>x</code> component by some value, or perhaps constraining the angular velocity to a reasonable range, could really help. Here’s the entire <code>update()</code> function with these tweaks added.</p>
|
||
<div data-type="example">
|
||
<h3 id="example-32-forces-with-arbitrary-angular-motion">Example 3.2: Forces with (Arbitrary) Angular Motion</h3>
|
||
<figure>
|
||
<div data-type="embed" data-p5-editor="https://editor.p5js.org/natureofcode/sketches/xj2C2Ldbo" data-example-path="examples/03_oscillation/example_3_2_forces_with_arbitrary_angular_motion"><img src="examples/03_oscillation/example_3_2_forces_with_arbitrary_angular_motion/screenshot.png"></div>
|
||
<figcaption></figcaption>
|
||
</figure>
|
||
</div>
|
||
<pre class="codesplit" data-code-language="javascript"> update() {
|
||
this.velocity.add(this.acceleration);
|
||
this.position.add(this.velocity);
|
||
|
||
//{!1} Calculate angular acceleration according to acceleration’s x component.
|
||
this.angleAcceleration = this.acceleration.x / 10.0;
|
||
this.angleVelocity += this.angleAcceleration;
|
||
//{!1} Use constrain() to ensure that angular velocity doesn’t spin out of control.
|
||
this.angleVelocity = constrain(this.angleVelocity, -0.1, 0.1);
|
||
this.angle += this.angleVelocity;
|
||
|
||
this.acceleration.mult(0);
|
||
}</pre>
|
||
<p>Notice that I’ve used multiple strategies to keep the object from spinning out of control. First, I divide <code>acceleration.x</code> by <code>10</code> before assigning it to <code>angleAcceleration</code>. Then, for good measure, I also use <code>constrain()</code> to confine <code>angleVelocity</code> to the range <code>(-0.1, 0.1)</code>.</p>
|
||
<div data-type="exercise">
|
||
<h3 id="exercise-33">Exercise 3.3</h3>
|
||
<p>Step 1: Create a simulation where objects are shot out of a cannon. Each object should experience a sudden force when shot (just once) as well as gravity (always present).</p>
|
||
<p>Step 2: Add rotation to the object to model its spin as it is shot from the cannon. How realistic can you make it look?</p>
|
||
</div>
|
||
<h2 id="trigonometry-functions">Trigonometry Functions</h2>
|
||
<p>I think I’m ready to reveal the secret of trigonometry. I’ve discussed angles, I’ve spun a baton. Now it’s time for … wait for it … <em>sohcahtoa</em>. Yes, <em>sohcahtoa! </em>This seemingly nonsensical word is actually the foundation for much of computer graphics work. A basic understanding of trigonometry is essential if you want to calculate angles, figure out distances between points, and work with circles, arcs, or lines. And <em>sohcahtoa</em> is a mnemonic device (albeit a somewhat absurd one) for remembering what the trigonometric functions sine, cosine, and tangent mean. It references the different sides of a right triangle, as shown in Figure 3.4.</p>
|
||
<figure>
|
||
<img src="images/03_oscillation/03_oscillation_4.png" alt="Figure 3.4: A right triangle showing the sides as adjacent, opposite, and hypotenuse">
|
||
<figcaption>Figure 3.4: A right triangle showing the sides as adjacent, opposite, and hypotenuse</figcaption>
|
||
</figure>
|
||
<p>Take one of the non-right angles in the triangle. The <em>adjacent</em> side is the one touching that angle, the <em>opposite</em> side is the one not touching that angle, and the <em>hypotenuse</em> is the side opposite the right angle. <em>Sohcahtoa</em> tells you how to calculate the angle’s trigonometric functions in terms of the lengths of these sides:</p>
|
||
<ul>
|
||
<li><strong><em>soh</em></strong><em>: </em><span data-type="equation">\text{\textbf{s}ine(angle)} = \text{\textbf{o}pposite}/\text{\textbf{h}ypotenuse}</span></li>
|
||
<li><strong><em>cah</em></strong>: <span data-type="equation">\text{\textbf{c}osine(angle)} = \text{\textbf{a}djacent} / \text{\textbf{h}ypotenuse}</span></li>
|
||
<li><strong><em>toa</em></strong>: <span data-type="equation">\text{\textbf{t}angent(angle)} = \text{\textbf{o}pposite} / \text{\textbf{a}djacent}</span></li>
|
||
</ul>
|
||
<p>Take a look at Figure 3.4 again. You don’t need to memorize it, but see if you feel comfortable with it. Try redrawing it yourself. Next, let’s look at it in a slightly different way (see Figure 3.5).</p>
|
||
<figure class="half-width-right">
|
||
<img src="images/03_oscillation/03_oscillation_5.png" alt="Figure 3.5: A vector \vec{v} with components x,y and angle.">
|
||
<figcaption>Figure 3.5: A vector <span data-type="equation">\vec{v}</span> with components <span data-type="equation">x,y</span> and <span data-type="equation">angle</span>.</figcaption>
|
||
</figure>
|
||
<p>See how a right triangle is created from the vector <span data-type="equation">\vec{v}</span>? The vector arrow itself is the hypotenuse and the components of the vector (<span data-type="equation">x</span> and <span data-type="equation">y</span>) are the sides of the triangle. The angle is an additional means for specifying the vector’s direction (or “heading”). Viewed in this way, the trigonometric functions establish a relationship between the components of a vector and its direction + magnitude. As such, trigonometry will prove very useful throughout this book. To illustrate this, let’s look at an example that requires the tangent function.</p>
|
||
<h2 id="pointing-in-the-direction-of-movement">Pointing in the Direction of Movement</h2>
|
||
<p>Think all the way back to Example 1.10, which featured a <code>Mover</code> object accelerating toward the mouse.</p>
|
||
<figure>
|
||
<div data-type="embed" data-p5-editor="https://editor.p5js.org/natureofcode/sketches/gYJHm1EFL" data-example-path="examples/03_oscillation/example_1_10_accelerating_towards_the_mouse"><img src="examples/03_oscillation/example_1_10_accelerating_towards_the_mouse/screenshot.png"></div>
|
||
<figcaption></figcaption>
|
||
</figure>
|
||
<p>You might notice that almost all of the shapes I’ve been drawing so far have been circles. This is convenient for a number of reasons, one of which is that it allowed me to avoid the question of rotation. Rotate a circle and, well, it looks exactly the same. Nevertheless, there comes a time in all motion programmers’ lives when they want to move something around on the screen that isn’t shaped like a circle. Perhaps it’s an ant, or a car, or a spaceship. To look realistic, that object should point in its direction of movement.</p>
|
||
<p>When I say “point in its direction of movement,” what I really mean is “rotate according to its velocity vector.” Velocity is a vector, with an <span data-type="equation">x</span> and a <span data-type="equation">y</span> component, but to rotate in p5.js you need one number, an angle. Let’s look at the trigonometry diagram once more, this time focused on an object’s velocity vector (Figure 3.6).</p>
|
||
<figure>
|
||
<img src="images/03_oscillation/03_oscillation_6.png" alt="Figure 3.6: The tangent of a velocity vector’s angle is y divided by x.">
|
||
<figcaption>Figure 3.6: The tangent of a velocity vector’s angle is <span data-type="equation">y</span> divided by <span data-type="equation">x</span>.</figcaption>
|
||
</figure>
|
||
<p>The vector’s <span data-type="equation">x</span> and <span data-type="equation">y</span> components are related to its angle through the tangent function. Using the <em>toa</em> in <em>sohcahtoa</em>, I can write the relationship as follows:</p>
|
||
<div data-type="equation">\text{tangent(angle)} = \frac{\text{velocity}_y}{\text{velocity}_x}</div>
|
||
<p>The problem here is that while I know the <span data-type="equation">x</span> and <span data-type="equation">y</span> components of the velocity vector, I don’t actually know the angle of its direction. I have to solve for that angle. This is where another function known as the <em>inverse tangent</em> or <em>arctangent</em> (<em>arctan</em> or <em>atan</em>, for short) comes in. (There are also <em>inverse sine</em> and an <em>inverse cosine</em> functions, called <em>arcsine</em> and <em>arccosine</em>, respectively.)</p>
|
||
<p>If the tangent of some value <span data-type="equation">a</span> equals some value <span data-type="equation">b</span>, then the inverse tangent of <span data-type="equation">b</span> equals <span data-type="equation">a</span>. For example:</p>
|
||
<table>
|
||
<tbody>
|
||
<tr>
|
||
<td>if</td>
|
||
<td><span data-type="equation">\tan(a) = b</span></td>
|
||
</tr>
|
||
<tr>
|
||
<td>then</td>
|
||
<td><span data-type="equation">a = \arctan(b)</span></td>
|
||
</tr>
|
||
</tbody>
|
||
</table>
|
||
<p>See how one is the inverse of the other? This allows me to solve for the vector’s angle:</p>
|
||
<table>
|
||
<tbody>
|
||
<tr>
|
||
<td>if</td>
|
||
<td><span data-type="equation">\tan(\text{angle}) = \frac{\text{velocity}_y}{\text{velocity}_x}</span></td>
|
||
</tr>
|
||
<tr>
|
||
<td>then</td>
|
||
<td><span data-type="equation">\text{angle} = \arctan(\frac{\text{velocity}_y}{\text{velocity}_x})</span></td>
|
||
</tr>
|
||
</tbody>
|
||
</table>
|
||
<p>Now that I have the formula, let’s see where it should go in the <code>Mover</code> class’s <code>show()</code> method to make the mover (now drawn as a rectangle) point in its direction of motion. Note that in p5.js, the function for inverse tangent is <code>atan()</code>.</p>
|
||
<pre class="codesplit" data-code-language="javascript"> show() {
|
||
//{!1} Solve for the angle using atan().
|
||
let angle = atan(this.velocity.y / this.velocity.x);
|
||
|
||
stroke(0);
|
||
fill(175);
|
||
push();
|
||
rectMode(CENTER);
|
||
translate(this.position.x, this.position.y);
|
||
//{!1} Rotate according to that angle.
|
||
rotate(angle);
|
||
rect(0, 0, 30, 10);
|
||
pop();
|
||
}</pre>
|
||
<figure class="half-width-right">
|
||
<img src="images/03_oscillation/03_oscillation_7.png" alt="Figure 3.7: The vectors \vec{v}_1 and \vec{v}_2 with components (4,-3) and (-4,3) point in opposite directions.">
|
||
<figcaption>Figure 3.7: The vectors <span data-type="equation">\vec{v}_1</span> and <span data-type="equation">\vec{v}_2</span> with components <span data-type="equation">(4,-3)</span> and <span data-type="equation">(-4,3)</span> point in opposite directions.</figcaption>
|
||
</figure>
|
||
<p>This code is pretty darn close, and almost works. There’s a big problem, though. Consider the two velocity vectors depicted in Figure 3.7.</p>
|
||
<p>Though superficially similar, the two vectors point in quite different directions—opposite directions, in fact! In spite of this, look at what happens if I apply the inverse tangent formula to solve for the angle of each vector:</p>
|
||
<div data-type="equation">\vec{v}_1 ⇒ \text{angle} = \arctan(3/-4) = \arctan(-0.75) = -0.643501 \text{ radians} = -37 \text{ degrees}</div>
|
||
<div data-type="equation">\vec{v}_2 ⇒ \text{angle} = \arctan(-3/4) = \arctan(-0.75) = -0.643501 \text{ radians} = -37 \text{ degrees}</div>
|
||
<p>I get the same angle! That can’t be right, though, since the vectors are pointing in opposite directions. It turns out this is a pretty common problem in computer graphics. I could use <code>atan()</code> along with conditional statements to account for positive/negative scenarios, but p5.js (along with most programming environments) has a helpful function called <code>atan2()</code> that resolves the issue for me.</p>
|
||
<div data-type="example">
|
||
<h3 id="example-33-pointing-in-the-direction-of-motion">Example 3.3: Pointing in the Direction of Motion</h3>
|
||
<figure>
|
||
<div data-type="embed" data-p5-editor="https://editor.p5js.org/natureofcode/sketches/bZqHGYbRQ" data-example-path="examples/03_oscillation/example_3_3_pointing_in_the_direction_of_motion"><img src="examples/03_oscillation/example_3_3_pointing_in_the_direction_of_motion/screenshot.png"></div>
|
||
<figcaption></figcaption>
|
||
</figure>
|
||
</div>
|
||
<pre class="codesplit" data-code-language="javascript"> show() {
|
||
//{!1} Using atan2() to account for all possible directions
|
||
let angle = atan2(this.velocity.y, this.velocity.x);
|
||
|
||
stroke(0);
|
||
fill(127);
|
||
push();
|
||
rectMode(CENTER);
|
||
translate(this.position.x, this.position.y);
|
||
//{!1} Rotate according to that angle.
|
||
rotate(angle);
|
||
rect(0, 0, 30, 10);
|
||
pop();
|
||
}</pre>
|
||
<p>To simplify this even further, the <code>p5.Vector</code> class itself provides a method called <code>heading()</code>, which takes care of calling <code>atan2()</code> and returns the 2D direction angle, in radians, for any <code>p5.Vector</code>.</p>
|
||
<pre class="codesplit" data-code-language="javascript"> // The easiest way to do this!
|
||
let angle = this.velocity.heading();</pre>
|
||
<p>With <code>heading()</code>, it turns out you don’t actually need to implement the trigonometry functions in your code, but it still helps to know how it’s all working.</p>
|
||
<div data-type="exercise">
|
||
<h3 id="exercise-33-1">Exercise 3.3</h3>
|
||
<p>Create a simulation of a vehicle that you can drive around the screen using the arrow keys: left arrow accelerates the car to the left, right to the right. The car should point in the direction in which it’s currently moving.</p>
|
||
</div>
|
||
<h2 id="polar-vs-cartesian-coordinates">Polar vs. Cartesian Coordinates</h2>
|
||
<p>Any time you draw a shape in p5.js, you have to specify a pixel position, a set of <span data-type="equation">x</span> and <span data-type="equation">y</span> coordinates. These coordinates are known as <strong>Cartesian coordinates</strong>, named for René Descartes, the French mathematician who developed the ideas behind Cartesian space.</p>
|
||
<p>Another useful coordinate system known as <strong>polar coordinates</strong> describes a point in space as a distance from the origin (like the radius of a circle) and an angle of rotation around the origin (usually called <span data-type="equation">\theta</span>, the Greek letter theta). Thinking in terms of vectors, a Cartesian coordinate describes a vector’s <span data-type="equation">x</span> and <span data-type="equation">y</span> components, whereas a polar coordinate describes a vector’s magnitude (length) and direction (angle).</p>
|
||
<p>When working in p5.js, you may find it more convenient to think in polar coordinates, especially when creating sketches that involve rotational or circular movements. However, p5.js’s drawing functions only understand <span data-type="equation">xy</span> Cartesian coordinates. Happily for you, trigonometry holds the key to converting back and forth between polar and Cartesian (see Figure 3.8). This allows you to design with whatever coordinate system you have in mind, while always drawing using Cartesian coordinates.</p>
|
||
<figure class="theta">
|
||
<img src="images/03_oscillation/03_oscillation_8.png" alt="Figure 3.8: The Greek letter \theta (theta) is often used to denote an angle. Since a polar coordinate is conventionally referred to as (r, \theta), I’ll use as a variable name when referring to an angle in p5.js.">
|
||
<figcaption>Figure 3.8: The Greek letter <span data-type="equation">\theta</span> (theta) is often used to denote an angle. Since a polar coordinate is conventionally referred to as <span data-type="equation">(r, \theta)</span>, I’ll use as a variable name when referring to an angle in p5.js.</figcaption>
|
||
</figure>
|
||
<p>For example, given a polar coordinate with a radius of 75 pixels and an angle (<span data-type="equation">\theta</span>) of 45 degrees (or <span data-type="equation">\pi/4</span> radians), the Cartesian <span data-type="equation">x</span> and <span data-type="equation">y</span> can be computed as follows:</p>
|
||
<div data-type="equation">\cos(\theta) = x/r → x = r \times \cos(\theta)</div>
|
||
<div data-type="equation">\sin(\theta) = y / r → y = r \times \sin(\theta)</div>
|
||
<p>The functions for sine and cosine in p5.js are <code>sin()</code> and <code>cos()</code>, respectively. They each take one argument, a number representing an angle in radians. These formulas can thus be coded as:</p>
|
||
<pre class="codesplit" data-code-language="javascript">let r = 75;
|
||
let theta = PI / 4;
|
||
// Converting from polar (r,theta) to Cartesian (x,y)
|
||
let x = r * cos(theta);
|
||
let y = r * sin(theta);</pre>
|
||
<p>This type of conversion can be useful in certain applications. For instance, moving a shape along a circular path using Cartesian coordinates isn’t so easy. However, with polar coordinates, it’s simple: just increment the angle! Here’s how it’s done with global <code>r</code> and <code>theta</code> variables.</p>
|
||
<div data-type="example">
|
||
<h3 id="example-34-polar-to-cartesian">Example 3.4: Polar to Cartesian</h3>
|
||
<figure>
|
||
<div data-type="embed" data-p5-editor="https://editor.p5js.org/natureofcode/sketches/qcnlfvP3q" data-example-path="examples/03_oscillation/example_3_4_polar_to_cartesian"><img src="examples/03_oscillation/example_3_4_polar_to_cartesian/screenshot.png"></div>
|
||
<figcaption></figcaption>
|
||
</figure>
|
||
</div>
|
||
<pre class="codesplit" data-code-language="javascript">let r;
|
||
let theta;
|
||
|
||
function setup() {
|
||
createCanvas(640, 240);
|
||
|
||
//{!2} Initialize all values
|
||
r = height * 0.45;
|
||
theta = 0;
|
||
}
|
||
|
||
function draw() {
|
||
background(255);
|
||
|
||
// Translate the origin point to the center of the screen
|
||
translate(width / 2, height / 2);
|
||
|
||
//{!2} Polar coordinates (r,theta) are converted to Cartesian (x,y) for use in the circle() function.
|
||
let x = r * cos(theta);
|
||
let y = r * sin(theta);
|
||
|
||
fill(127);
|
||
stroke(0);
|
||
line(0, 0, x, y);
|
||
circle(x, y, 48);
|
||
|
||
// Increase the angle over time
|
||
theta += 0.02;
|
||
}</pre>
|
||
<p>Polar to Cartesian conversion is common enough that p5.js includes as handy function to take care of it for you. It’s included as a static method of the <code>p5.Vector</code> class called <code>fromAngle()</code>. It takes an angle in radians and creates a unit vector in Cartesian space that points in the direction specified by the angle. Here’s how that would look in Example 3.4.</p>
|
||
<pre class="codesplit" data-code-language="javascript"> // Create a unit vector pointing in the direction of an angle.
|
||
let position = p5.Vector.fromAngle(theta);
|
||
// To complete polar to Cartesian conversion, scale the vector by r.
|
||
position.mult(r);
|
||
// Draw the circle using the x,y components of the vector.
|
||
circle(position.x, position.y, 48);</pre>
|
||
<p>Are you amazed yet? I’ve demonstrated some pretty great uses of tangent (for finding the angle of a vector) and sine and cosine (for converting from polar to Cartesian coordinates). I could stop right here and be satisfied. But I’m not going to. This is only the beginning. As I’ll show you next, what sine and cosine can do for you goes beyond mathematical formulas and right triangles.</p>
|
||
<div data-type="exercise">
|
||
<h3 id="exercise-34">Exercise 3.4</h3>
|
||
<p>Using Example 3.4 as a basis, draw a spiral path. Start in the center and move outward. Note that this can be done by only changing one line of code and adding one line of code!</p>
|
||
<figure>
|
||
<div data-type="embed" data-p5-editor="https://editor.p5js.org/natureofcode/sketches/qTs23wBBs" data-example-path="examples/03_oscillation/exercise_3_4_spiral"><img src="examples/03_oscillation/exercise_3_4_spiral/screenshot.png"></div>
|
||
<figcaption></figcaption>
|
||
</figure>
|
||
</div>
|
||
<div data-type="exercise">
|
||
<h3 id="exercise-35">Exercise 3.5</h3>
|
||
<p>Simulate the spaceship in the game <em>Asteroids</em>. In case you aren’t familiar with <em>Asteroids</em>, here’s a brief description: A spaceship (represented as a triangle) floats in two-dimensional space. The left arrow key turns the spaceship counterclockwise, the right arrow key, clockwise. The <em>z</em> key applies a “thrust” force in the direction the spaceship is pointing. </p>
|
||
<figure>
|
||
<div data-type="embed" data-p5-editor="https://editor.p5js.org/natureofcode/sketches/7jQEBLJhX" data-example-path="examples/03_oscillation/exercise_3_5_asteroids"><img src="examples/03_oscillation/exercise_3_5_asteroids/screenshot.png"></div>
|
||
<figcaption></figcaption>
|
||
</figure>
|
||
</div>
|
||
<h2 id="properties-of-oscillation">Properties of Oscillation</h2>
|
||
<p>Take a look at the graph of the sine function in Figure 3.9, where <span data-type="equation">y = \sin(x)</span>.</p>
|
||
<figure>
|
||
<img src="images/03_oscillation/03_oscillation_9.png" alt="Figure 3.9: A graph of y = sin(x)">
|
||
<figcaption>Figure 3.9: A graph of <span data-type="equation">y = sin(x)</span></figcaption>
|
||
</figure>
|
||
<p>The output of the sine function is a smooth curve alternating between <span data-type="equation">−1</span> and <span data-type="equation">1</span>, also known as a <strong>sine wave</strong>. This behavior, a periodic movement between two points, is the <strong>oscillation</strong> I mentioned at the start of the chapter. Plucking a guitar string, swinging a pendulum, bouncing on a pogo stick—these are all examples of oscillating motion, and they can all be modeled using the sine function.</p>
|
||
<p>In a p5.js sketch, you can simulate oscillation by assigning the output of the sine function to an object’s position. I’ll begin with a basic scenario: I want a circle to oscillate between the left side and the right side of a canvas.</p>
|
||
<figure>
|
||
<div data-type="embed" data-p5-editor="https://editor.p5js.org/natureofcode/sketches/O8LMHH-Df" data-example-path="examples/03_oscillation/example_3_5_simple_harmonic_motion"><img src="examples/03_oscillation/example_3_5_simple_harmonic_motion/screenshot.png"></div>
|
||
<figcaption></figcaption>
|
||
</figure>
|
||
<p>This pattern of oscillating back and forth around a central point is known as <strong>simple harmonic motion</strong> (or, to be fancier, “the periodic sinusoidal oscillation of an object”). The code to achieve it is remarkably simple, but before I get into it, I’d like to introduce some of the key terminology related to oscillation (and waves).</p>
|
||
<p>When a moving object exhibits simple harmonic motion, its position (in this case, the <span data-type="equation">x</span> position) can be expressed as a function of time, with the following two elements:</p>
|
||
<ul>
|
||
<li><strong>Amplitude</strong>: The distance from the center of motion to either extreme</li>
|
||
<li><strong>Period</strong>: The duration (time) for one complete cycle of motion</li>
|
||
</ul>
|
||
<p>To understand these terms, look again at the graph of the sine function in Figure 3.9. The curve never rises above <span data-type="equation">1</span> or below <span data-type="equation">-1</span> along the y-axis, so the sine function has an amplitude of <span data-type="equation">1</span>. Meanwhile, the wave pattern of the curve repeats every <span data-type="equation">2\pi</span> units along the x-axis, so the sine function’s period is <span data-type="equation">2\pi</span>. (By convention, the units here are radians, since the input value to the sine function is customarily an angle measured in radians.)</p>
|
||
<p>So much for the amplitude and period of an abstract sine function, but what are amplitude and period in the p5.js world of an oscillating circle? Well, amplitude can be measured rather easily in pixels. For example, if the canvas is 200 pixels wide, I might choose to oscillate around the center of the canvas, going between 100 pixels right of center and 100 pixels left of center. In other words, the amplitude is 100 pixels:</p>
|
||
<pre class="codesplit" data-code-language="javascript">// The amplitude is measured in pixels.
|
||
let amplitude = 100;</pre>
|
||
<p>The period is the amount of time for one complete cycle of an oscillation. However, in a p5.js sketch, what does “time” really mean? In theory, I could say I want the circle to oscillate every three seconds, then come up with an elaborate algorithm for moving the object according to real-world time, using <code>millis()</code> to track the passage of milliseconds. For what I‘m trying to accomplish here, however, real-world time isn’t necessary. The more useful measure of time in p5.js is how many <strong>frames</strong> have elapsed, available through the built-in <code>frameCount</code> variable. Do I want the oscillating motion to repeat every 30 frames? Every 50 frames? For now, how about a period of 120 frames:</p>
|
||
<pre class="codesplit" data-code-language="javascript">// Period is measured in frames (the unit of time for animation).
|
||
let period = 120;</pre>
|
||
<p>Once I have the amplitude and period, it’s time to write a formula to calculate the circle’s <span data-type="equation">x</span> position as a function of time (the current frame count):</p>
|
||
<pre class="codesplit" data-code-language="javascript">// amplitude and period are my own variables, frameCount is built into p5.js
|
||
let x = amplitude * sin(TWO_PI * frameCount / period);</pre>
|
||
<p>Think about what’s going here. First, whatever value the <code>sin()</code> function returns is multiplied by <code>amplitude</code>. As you saw in Figure 3.9, the output of the sine function oscillates between <span data-type="equation">-1</span> and <span data-type="equation">1</span>. Multiplying that value by my chosen amplitude—call it <span data-type="equation">a</span>—gives me the desired result: a value that oscillates between <span data-type="equation">-a</span> and <span data-type="equation">a</span>. (This is also a place where you could use p5.js’s <code>map()</code> function to map the output of <code>sin()</code> to a custom range.)</p>
|
||
<p>Now, think about what’s inside the <code>sin()</code> function:</p>
|
||
<pre class="codesplit" data-code-language="javascript">TWO_PI * frameCount / period</pre>
|
||
<p>What’s going on here? Start with what you know. I‘ve explained that sine has a period of <span data-type="equation">2\pi</span>, meaning it will start at <span data-type="equation">0</span> and repeat at <span data-type="equation">2\pi</span>, <span data-type="equation">4\pi</span>, <span data-type="equation">6\pi</span>, and so on. If my desired period of oscillation is 120 frames, then I want the circle to be in the same position when <code>frameCount</code> is at 120 frames, 240 frames, 360 frames, and so on. Here, <code>frameCount</code> is the only value changing over time; it starts at 0 and counts upward. Let’s take a look at what the formula yields as <code>frameCount</code> increases.</p>
|
||
<table>
|
||
<thead>
|
||
<tr>
|
||
<th><code>frameCount</code></th>
|
||
<th><code>frameCount / period</code></th>
|
||
<th><code>TWO_PI * frameCount / period</code></th>
|
||
</tr>
|
||
</thead>
|
||
<tbody>
|
||
<tr>
|
||
<td>0</td>
|
||
<td>0</td>
|
||
<td>0</td>
|
||
</tr>
|
||
<tr>
|
||
<td>60</td>
|
||
<td>0.5</td>
|
||
<td><span data-type="equation">\pi</span></td>
|
||
</tr>
|
||
<tr>
|
||
<td>120</td>
|
||
<td>1</td>
|
||
<td><span data-type="equation">2\pi</span></td>
|
||
</tr>
|
||
<tr>
|
||
<td>240</td>
|
||
<td>2</td>
|
||
<td><span data-type="equation">4\pi</span></td>
|
||
</tr>
|
||
<tr>
|
||
<td>etc.</td>
|
||
<td>etc.</td>
|
||
<td>etc.</td>
|
||
</tr>
|
||
</tbody>
|
||
</table>
|
||
<p>Dividing <code>frameCount</code> by <code>period</code> tells me how many cycles have been completed. (Is the wave halfway through the first cycle? Have two cycles completed?) Multiplying that number by <code>TWO_PI</code>, I get the desired result, an appropriate input to the <code>sin()</code> function, since <code>TWO_PI</code> is the value required for sine (or cosine) to complete one full cycle.</p>
|
||
<p>Putting it together, here’s an example that oscillates the <code>x</code> position of a circle with an amplitude of 100 pixels and a period of 120 frames.</p>
|
||
<div data-type="example">
|
||
<h3 id="example-35-simple-harmonic-motion">Example 3.5: Simple Harmonic Motion</h3>
|
||
<figure>
|
||
<div data-type="embed" data-p5-editor="https://editor.p5js.org/natureofcode/sketches/O8LMHH-Df" data-example-path="examples/03_oscillation/example_3_5_simple_harmonic_motion"><img src="examples/03_oscillation/example_3_5_simple_harmonic_motion/screenshot.png"></div>
|
||
<figcaption></figcaption>
|
||
</figure>
|
||
</div>
|
||
<pre class="codesplit" data-code-language="javascript">function setup() {
|
||
createCanvas(640, 240);
|
||
}
|
||
|
||
function draw() {
|
||
background(255);
|
||
|
||
let period = 120;
|
||
let amplitude = 200;
|
||
|
||
//{!1 .offset} Calculating horizontal position according to the formula for simple harmonic motion
|
||
let x = amplitude * sin(TWO_PI * frameCount / period);
|
||
|
||
stroke(0);
|
||
fill(127);
|
||
translate(width / 2, height / 2);
|
||
line(0, 0, x, 0);
|
||
circle(x, 0, 48);
|
||
}</pre>
|
||
<p>Before moving on, I would be remiss not to mention <strong>frequency</strong>, the number of cycles of an oscillation per time unit. Frequency is the inverse of the period: 1 divided by period. For example, if the period is 120 frames, then only 1/120th of a cycle is completed in 1 frame, and so the frequency is 1/120. In Example 3.5, I chose to define the rate of oscillation in terms of period, and therefore I didn’t need a variable for frequency. Sometimes, however, thinking in terms of frequency rather than period is more useful.</p>
|
||
<p></p>
|
||
<div data-type="exercise">
|
||
<h3 id="exercise-36">Exercise 3.6</h3>
|
||
<p>Using the sine function, create a simulation of a weight (sometimes referred to as a “bob”) that hangs from a spring from the top of the window. Use the <code>map()</code> function to calculate the vertical position of the bob. Later in this chapter, I’ll demonstrate how to create this same simulation by modeling the forces of a spring according to Hooke’s law.</p>
|
||
</div>
|
||
<h2 id="oscillation-with-angular-velocity">Oscillation with Angular Velocity</h2>
|
||
<p>An understanding of the concepts of oscillation, amplitude, and period (or frequency) can be essential in the course of simulating real-world behaviors. However, there’s a slightly easier way to implement the simple harmonic motion from Example 3.5, one that achieves the same result with fewer variables. Take one more look at the oscillation formula:</p>
|
||
<pre class="codesplit" data-code-language="javascript">let x = amplitude * sin(TWO_PI * frameCount / period);</pre>
|
||
<p>Now I‘ll rewrite it a slightly different way:</p>
|
||
<pre class="codesplit" data-code-language="javascript">let x = amplitude * sin ( <strong>some value that increments slowly</strong> );</pre>
|
||
<p>If you care about precisely defining the period of oscillation in terms of frames of animation, you might need the formula as I first wrote it. If you don’t care about the exact period, however—for example, if you’ll be choosing it randomly—all you really need inside the <code>sin()</code> function is some value that increments slowly enough for the object’s motion to appear smooth from one frame to the next. Every time this value ticks past a multiple of <span data-type="equation">2\pi</span>, the object will have completed one cycle of oscillation.</p>
|
||
<p>The technique here mirrors what I did with Perlin noise in the Chapter 0. In that case, I incremented an “offset” variable (which I called <code>t</code> or <code>xoff</code>) to sample different outputs from the <code>noise()</code> function, creating a smooth transition of values. Now, I’m going to increment a value (I’ll call it <code>angle</code>) that's fed into the <code>sin()</code> function. The difference is that the output from <code>sin()</code> is a smoothly repeating sine wave, without any randomness.</p>
|
||
<p>You might be wondering why I refer to the incrementing value as <code>angle</code> given that there’s no visible rotation of the object itself. The term <em>angle</em> is used because the value is passed into the <code>sin()</code> function, and angles are the traditional inputs to trigonometric functions. With this in mind, I can reintroduce the concept of angular velocity (and acceleration) to rewrite the example to calculate the <code>x</code> position in terms of a changing angle. I’ll assume these global variables:</p>
|
||
<pre class="codesplit" data-code-language="javascript">let angle = 0;
|
||
let angleVelocity = 0.05;</pre>
|
||
<p>I can then write:</p>
|
||
<pre class="codesplit" data-code-language="javascript">function draw() {
|
||
angle += angleVelocity;
|
||
let x = amplitude * sin(angle);
|
||
}</pre>
|
||
<p>Here <code>angle</code> is my “some value that increments slowly,” and the amount it slowly increments by is <code>angleVelocity</code>.</p>
|
||
<div data-type="example">
|
||
<h3 id="example-36-simple-harmonic-motion-ii">Example 3.6: Simple Harmonic Motion II</h3>
|
||
<figure>
|
||
<div data-type="embed" data-p5-editor="https://editor.p5js.org/natureofcode/sketches/gwdC8X-W-j" data-example-path="examples/03_oscillation/example_3_6_simple_harmonic_motion_ii"><img src="examples/03_oscillation/example_3_6_simple_harmonic_motion_ii/screenshot.png"></div>
|
||
<figcaption></figcaption>
|
||
</figure>
|
||
</div>
|
||
<pre class="codesplit" data-code-language="javascript">let angle = 0;
|
||
let angleVelocity = 0.05;
|
||
|
||
function setup() {
|
||
createCanvas(640, 240);
|
||
}
|
||
|
||
function draw() {
|
||
background(255);
|
||
|
||
let amplitude = 200;
|
||
let x = amplitude * sin(angle);
|
||
//{!1} Using the concept of angular velocity to increment an angle variable
|
||
angle += angleVelocity;
|
||
|
||
translate(width / 2, height / 2);
|
||
|
||
stroke(0);
|
||
fill(127);
|
||
line(0, 0, x, 0);
|
||
circle(x, 0, 48);
|
||
}</pre>
|
||
<p>Just because I’m not referencing it directly doesn’t mean that I’ve eliminated the concept of period. After all, the greater the angular velocity, the faster the circle will oscillate (and therefore the shorter the period). In fact, the period is the number of frames it takes for <code>angle</code> to increment by <span data-type="equation">2\pi</span>. Since the amount <code>angle</code> increments is controlled by the angular velocity, I can calculate the period as:</p>
|
||
<div data-type="equation">\text{period} = 2\pi / \text{angular velocity}</div>
|
||
<p>To illustrate the power of thinking of oscillation in terms of angular velocity, I’ll expand the example a bit more by creating an <code>Oscillator</code> class whose objects can oscillate independently along both the x-axis (as before) <em>and</em> the y-axis. The class will need two angles, two angular velocities, and two amplitudes (one for each axis). This is a perfect opportunity to use <code>createVector()</code> to package each pair of values together! Unlike previous vectors, the values in these vectors won’t be sets of Cartesian coordinates. Nevertheless, the <code>p5.Vector</code> class provides a convenient way to manage pairs of values—in this case, pairs of angles (and their associated velocities, accelerations, and so on).</p>
|
||
<div data-type="example">
|
||
<h3 id="example-37-oscillator-objects">Example 3.7: Oscillator Objects</h3>
|
||
<figure>
|
||
<div data-type="embed" data-p5-editor="https://editor.p5js.org/natureofcode/sketches/b3HpgJa6F" data-example-path="examples/03_oscillation/example_3_7_oscillator_objects"><img src="examples/03_oscillation/example_3_7_oscillator_objects/screenshot.png"></div>
|
||
<figcaption></figcaption>
|
||
</figure>
|
||
</div>
|
||
<pre class="codesplit" data-code-language="javascript">class Oscillator {
|
||
constructor() {
|
||
//{!3} Using a p5.Vector to track two angles!
|
||
this.angle = createVector();
|
||
this.angleVelocity = createVector(random(-0.05, 0.05),random(-0.05, 0.05));
|
||
//{!1 .offset} Random velocities and amplitudes
|
||
this.amplitude = createVector(random(20, width / 2), random(20, height / 2));
|
||
}
|
||
|
||
update() {
|
||
this.angle.add(this.angleVelocity);
|
||
}
|
||
|
||
show() {
|
||
// Oscillating on the x-axis
|
||
let x = sin(this.angle.x) * this.amplitude.x;
|
||
//{!1} Oscillating on the y-axis
|
||
let y = sin(this.angle.y) * this.amplitude.y;
|
||
|
||
push();
|
||
translate(width / 2, height / 2);
|
||
stroke(0);
|
||
fill(127);
|
||
// Drawing the Oscillator as a line connecting a circle
|
||
line(0, 0, x, y);
|
||
circle(x, y, 32);
|
||
pop();
|
||
}
|
||
}</pre>
|
||
<p>To better understand the <code>Oscillator</code> class, it might be helpful to focus on the movement of a single oscillator in the animation. First, observe its horizontal movement. You'll notice that it oscillates regularly back and forth along the x-axis. Switching your focus to its vertical movement, you'll see it oscillating up and down along the y-axis. Each oscillator has its own distinct rhythm, given the random initialization of its angle, angular velocity, and amplitude.</p>
|
||
<p>The key is to recognize that the <code>x</code> and <code>y</code> properties of the <code>p5.Vector</code> objects <code>this.angle</code>, <code>this.angleVelocity</code>, and <code>this.amplitude</code> aren’t tied to spatial vectors anymore. Instead, they’re used to store the respective properties for two separate oscillations (one along the x-axis, one along the y-axis). Ultimately, these oscillations are manifested spatially when <code>x</code> and <code>y</code> are calculated in the <code>show()</code> method, mapping the oscillations onto the positions of the object.</p>
|
||
<div data-type="exercise">
|
||
<h3 id="exercise-37">Exercise 3.7</h3>
|
||
<p>Try initializing each <code>Oscillator</code> object with velocities and amplitudes that aren’t random to create some sort of regular pattern. Can you make the oscillators appear to be the legs of an insect-like creature?</p>
|
||
</div>
|
||
<div data-type="exercise">
|
||
<h3 id="exercise-38">Exercise 3.8</h3>
|
||
<p>Incorporate angular acceleration into the <code>Oscillator</code> object.</p>
|
||
</div>
|
||
<h2 id="waves">Waves</h2>
|
||
<p>Imagine a single circle oscillating up and down according to the sine function. This is the equivalent to simulating a single point along the x-axis of a wave pattern. With a little panache and a <code>for</code> loop, you can animate the entire wave by placing a whole bunch of these oscillating circles next to each other.</p>
|
||
<figure>
|
||
<div data-type="embed" data-p5-editor="https://editor.p5js.org/natureofcode/sketches/qe6oK9F1o" data-example-path="examples/03_oscillation/example_3_9_the_wave"><img src="examples/03_oscillation/example_3_9_the_wave/screenshot.png"></div>
|
||
<figcaption></figcaption>
|
||
</figure>
|
||
<p>You could use this wavy pattern to design the body or appendages of a creature, or to simulate a soft surface (such as water). Let’s dive into how the code for this sketch works.</p>
|
||
<p>Here, the same questions of amplitude (height of wave) and period apply. Since the example draws the full wave, however, the period no longer refers to time but rather to the width (in pixels) of a full wave cycle. And just as with the previous oscillation example, you have the option of computing the wave pattern according to a precise period or following the model of angular velocity.</p>
|
||
<p>I’ll go with the simpler case, angular velocity. I know I need three variables: an angle, an angular velocity, and an amplitude.</p>
|
||
<pre class="codesplit" data-code-language="javascript">let angle = 0;
|
||
let angleVelocity = 0.2;
|
||
let amplitude = 100;</pre>
|
||
<p>Then I’m going to loop through all of the <code>x</code> values for each point on the wave. For now, I’ll put 24 pixels between adjacent <code>x</code> values. For each <code>x</code>, I’ll follow these three steps:</p>
|
||
<ol>
|
||
<li>Calculate the <span data-type="equation">y</span> position according to amplitude and the sine of the angle.</li>
|
||
<li>Draw a circle at the <span data-type="equation">x,y</span> position.</li>
|
||
<li>Increment the angle by angular velocity.</li>
|
||
</ol>
|
||
<p>Translating these steps into code:</p>
|
||
<div data-type="example">
|
||
<h3 id="example-38-static-wave">Example 3.8: Static Wave</h3>
|
||
<figure>
|
||
<div data-type="embed" data-p5-editor="https://editor.p5js.org/natureofcode/sketches/CQ19Yw0iT" data-example-path="examples/03_oscillation/example_3_8_static_wave"><img src="examples/03_oscillation/example_3_8_static_wave/screenshot.png"></div>
|
||
<figcaption></figcaption>
|
||
</figure>
|
||
</div>
|
||
<pre class="codesplit" data-code-language="javascript">let angle = 0;
|
||
let angleVelocity = 0.2;
|
||
let amplitude = 100;
|
||
|
||
function setup() {
|
||
createCanvas(640, 240);
|
||
background(255);
|
||
|
||
stroke(0);
|
||
fill(127, 127);
|
||
|
||
for (let x = 0; x <= width; x += 24) {
|
||
// 1) Calculate the y position according to amplitude and sine of the angle.
|
||
let y = amplitude * sin(angle);
|
||
// 2) Draw a circle at the (x,y) position.
|
||
circle(x, y + height / 2, 48);
|
||
// 3) Increment the angle according to angular velocity.
|
||
angle += angleVelocity;
|
||
}
|
||
}</pre>
|
||
<p>What happens if you try different values for <code>angleVelocity</code>?</p>
|
||
<figure>
|
||
<div class="col-list">
|
||
<div>
|
||
<div data-type="embed" data-p5-editor="https://editor.p5js.org/natureofcode/sketches/S9l2FSS_M" data-example-path="examples/03_oscillation/example_3_9_the_wave_a"></div>
|
||
</div>
|
||
<div>
|
||
<div data-type="embed" data-p5-editor="https://editor.p5js.org/natureofcode/sketches/0oH4O6Y0d" data-example-path="examples/03_oscillation/example_3_9_the_wave_b"></div>
|
||
</div>
|
||
<div>
|
||
<div data-type="embed" data-p5-editor="https://editor.p5js.org/natureofcode/sketches/3msqsP8ZD" data-example-path="examples/03_oscillation/example_3_9_the_wave_c"></div>
|
||
</div>
|
||
</div>
|
||
<figcaption>Three sine waves with varying angleVelocity values (0.05, 0.2, 0.6 from left to right)</figcaption>
|
||
</figure>
|
||
<p>Although I’m not precisely calculating the period of the wave, you can see that the higher the angular velocity, the shorter the period. It’s also worth noting that as the period decreases, it becomes more difficult to make out the wave itself since the vertical distance between the individual points increases.</p>
|
||
<p>Notice that everything in Example 3.8 happens inside <code>setup()</code>, so the result is static. The wave never changes or undulates. Adding motion is a bit tricky. Your first instinct might be to say: “Hey, no problem, I’ll just put the <code>for</code> loop inside the <code>draw()</code> function and let <code>angle</code> continue incrementing from one cycle to the next.”</p>
|
||
<p><strong><em>Note for Nathan</em></strong></p>
|
||
<p>That’s a nice thought, but it doesn’t work. If you try it out, the result will appear extremely erratic and glitchy. To understand why, look back at Example 3.8. The right edge of the wave doesn’t match the height of the left edge, so where the wave ends in one cycle of <code>draw()</code> can’t be where it starts in the next. Instead, what you need is a variable dedicated entirely to tracking the starting <code>angle</code> value in each frame of the animation. This variable (which I’ll call <code>startAngle</code>) increments at its own pace, controlling how much the wave progresses from one frame to the next.</p>
|
||
<div data-type="example">
|
||
<h3 id="example-39-the-wave">Example 3.9: The Wave</h3>
|
||
<figure>
|
||
<div data-type="embed" data-p5-editor="https://editor.p5js.org/natureofcode/sketches/qe6oK9F1o" data-example-path="examples/03_oscillation/example_3_9_the_wave"><img src="examples/03_oscillation/example_3_9_the_wave/screenshot.png"></div>
|
||
<figcaption></figcaption>
|
||
</figure>
|
||
</div>
|
||
<pre class="codesplit" data-code-language="javascript">//{!1} A new global variable tracking the starting angle of the wave
|
||
let startAngle = 0;
|
||
let angleVelocity = 0.2;
|
||
|
||
function setup() {
|
||
createCanvas(640, 240);
|
||
}
|
||
|
||
function draw() {
|
||
background(255);
|
||
|
||
//{!1}Each time through draw, the angle that increments is set to startAngle
|
||
let angle = startAngle;
|
||
|
||
for (let x = 0; x <= width; x += 24) {
|
||
let y = map(sin(angle), -1, 1, 0, height);
|
||
stroke(0);
|
||
fill(127, 127);
|
||
circle(x, y, 48);
|
||
angle += angleVelocity;
|
||
}
|
||
|
||
//{!1} Increment starting angle.
|
||
startAngle += 0.02;
|
||
}</pre>
|
||
<p>In this code example, the increment of <code>startAngle</code> is hardcoded to be <code>0.02</code>, but you may want to consider reusing <code>angleVelocity</code> or creating a second variable instead. By reusing <code>angleVelocity</code>, the progression of the wave would be tied to the oscillation, possibly creating a more synchronized movement. Introducing a separate variable, perhaps called <code>startAngleVelocity</code>, would allow independent control of the speed of the wave.</p>
|
||
<div data-type="exercise">
|
||
<h3 id="exercise-39">Exercise 3.9</h3>
|
||
<p>Try using the Perlin noise function instead of sine or cosine to set the <code>y</code> values in Example 3.9.</p>
|
||
</div>
|
||
<div data-type="exercise">
|
||
<h3 id="exercise-310">Exercise 3.10</h3>
|
||
<p>Encapsulate the wave-generating code into a <code>Wave</code> class, and create a sketch that displays two waves (with different amplitudes/periods), as shown below. Try moving beyond plain circles and lines to visualize the wave in a more creative way. What about connecting the points using <code>beginShape()</code>, <code>endShape()</code>, and <code>vertex()</code>?</p>
|
||
<figure>
|
||
<div data-type="embed" data-p5-editor="https://editor.p5js.org/natureofcode/sketches/pHZjnSDrR" data-example-path="examples/03_oscillation/exercise_3_10_oop_wave"><img src="examples/03_oscillation/exercise_3_10_oop_wave/screenshot.png"></div>
|
||
<figcaption></figcaption>
|
||
</figure>
|
||
</div>
|
||
<div data-type="exercise">
|
||
<h3 id="exercise-311">Exercise 3.11</h3>
|
||
<p>To create more complex waves, you can add multiple waves together. Calculate the height (or <code>y</code>) values for several different waves, and add those values together to get a single <code>y</code> value. The result is a new wave that incorporates the characteristics of each individual wave.</p>
|
||
<figure>
|
||
<div data-type="embed" data-p5-editor="https://editor.p5js.org/natureofcode/sketches/lUxbHeeHLH" data-example-path="examples/03_oscillation/exercise_3_11_additive_wave"><img src="examples/03_oscillation/exercise_3_11_additive_wave/screenshot.png"></div>
|
||
<figcaption></figcaption>
|
||
</figure>
|
||
</div>
|
||
<h2 id="trigonometry-and-forces-the-pendulum">Trigonometry and Forces: The Pendulum</h2>
|
||
<p>It’s been nice delving into the mathematics of triangles and waves, but perhaps you’re starting to miss Newton’s laws of motion. After all, the core of this book is about simulating the physics of moving bodies. Before you write off all this trigonometry stuff as a tangent, allow me to show an example of how it all fits together. I’ll combine what you’ve learned about forces and trigonometry by modeling the motion of a pendulum.</p>
|
||
<figure class="half-width-right">
|
||
<img src="images/03_oscillation/03_oscillation_10.png" alt="Figure 3.10: A pendulum with a pivot, arm, and bob">
|
||
<figcaption>Figure 3.10: A pendulum with a pivot, arm, and bob</figcaption>
|
||
</figure>
|
||
<p>A <strong>pendulum</strong> is a weight, or bob, suspended by an arm from a pivot. When it’s at rest, the pendulum hangs straight down, as in Figure 3.10. If you lift the pendulum up at an angle from its resting state and then release it, however, it starts to swing back and forth, tracing the shape of an arc. A real-world pendulum would live in a three-dimensional space, but I’m going to look at a simpler scenario: a pendulum in the two-dimensional space of a p5.js canvas.</p>
|
||
<figure class="half-width-right">
|
||
<img src="images/03_oscillation/03_oscillation_11.png" alt="Figure 3.11: A pendulum showing \theta as angle relative to its resting position">
|
||
<figcaption>Figure 3.11: A pendulum showing <span data-type="equation">\theta</span> as angle relative to its resting position</figcaption>
|
||
</figure>
|
||
<p></p>
|
||
<p>When the pendulum swings, its arm and bob are essentially rotating around the fixed point of the pivot. Its motion can therefore be described in terms of <em>angular</em> acceleration and velocity, the change of the arm’s angle <span data-type="equation">\theta</span> relative to the pendulum’s resting position (see Figure 3.11). In Chapter 2, I discussed how forces cause an object to accelerate. Two main forces will contribute to my model pendulum’s angular acceleration vector.</p>
|
||
<p>The first force is gravity. As shown in Figure 3.11, this force is a vector that points straight down. If there were no arm connecting the bob and the pivot, the bob would simply fall to the ground under the influence of this force. Obviously, that isn’t what happens. Instead, the fixed length of the arm creates the second force—tension. Combined together, the resulting net force (which I’ll denote as <span data-type="equation">F_p</span> (see Figure 3.12) points toward the pendulum’s resting position, perpendicular to the arm. This net pendulum force, the result of gravity and tension, causes the pendulum swing back and forth.</p>
|
||
<p>To actually calculate the pendulum’s angular acceleration, I’m going to use Newton’s second law of motion, but with a little trigonometric twist. The key is to recognize the relationship between the gravity and the net pendulum force, as shown in Figure 3.12.</p>
|
||
<figure>
|
||
<img src="images/03_oscillation/03_oscillation_12.png" alt="Figure 3.12: A diagram of pendulum showing \sin(\theta) = F_p / F_g">
|
||
<figcaption>Figure 3.12: A diagram of pendulum showing <span data-type="equation">\sin(\theta) = F_p / F_g</span></figcaption>
|
||
</figure>
|
||
<p>The force of the pendulum (<span data-type="equation">F_p</span>) and the force of gravity (<span data-type="equation">F_g</span>) originate from the same point, the center of the bob. <span data-type="equation">F_p</span> is perpendicular to the arm of the pendulum, pointing in the direction of the resting position, and <span data-type="equation">F_g</span> points straight down. Draw an extra line connecting the ends of these two vectors and you’ll see something quite magnificent: a right triangle! Better still, one of the triangle’s angles is the same as the angle <span data-type="equation">\theta</span> between the pendulum’s arm and its resting position. The force of gravity is the hypotenuse of this right triangle, and the force of the pendulum is the side opposite <span data-type="equation">\theta</span>. Since sine equals opposite over hypotenuse, you then have:</p>
|
||
<div data-type="equation">\sin(\theta) = F_p / F_g</div>
|
||
<p>Or, thinking in terms of the force of the pendulum:</p>
|
||
<div data-type="equation">F_p = F_g\sin(\theta)</div>
|
||
<p>Lest you forget, my goal is to determine the angular acceleration of the pendulum. Once I have that, I’ll be able to apply the rules of motion to find a new angle <span data-type="equation">\theta</span> for each frame of the animation:</p>
|
||
<div data-type="equation">\text{angular velocity} = \text{angular velocity} + \text{angular acceleration}</div>
|
||
<div data-type="equation">\text{angle} = \text{angle + angular velocity}</div>
|
||
<p>The good news is that Newton’s second law establishes a relationship between force and acceleration, namely <span data-type="equation">F = M \times A</span>, or <span data-type="equation">A = F / M</span>. So if the force of the pendulum is equal to the force of gravity times the sine of the angle, then:</p>
|
||
<div data-type="equation">\text{pendulum angular acceleration} = \text{acceleration due to gravity} \times \sin(\theta)</div>
|
||
<p>This is a good time for a reminder that the context here is creative coding and not pure physics. Yes, the acceleration due to gravity on Earth is 9.8 meters per second squared. But this number isn’t relevant here in the world of pixels. Instead, I’ll use an arbitrary constant (called <code>gravity</code>) as a variable that scales the acceleration.</p>
|
||
<div data-type="equation">\text{angular acceleration} = \text{gravity} \times \sin(\theta)</div>
|
||
<p>Amazing! In the end, the formula is so simple that you might be wondering why I bothered going through the derivation at all. I mean, learning is great, but I could have easily just said, “Hey, the angular acceleration of a pendulum is some constant times the sine of the angle.” That would be missing the point. The purpose of this book isn’t to learn how pendulums swing or gravity works. The point is to think creatively about how shapes can move around a screen in a computationally based graphics system. The pendulum is just a case study. If you can understand the approach to programming a pendulum, you can apply the same techniques to other scenarios, no matter how you choose to design your p5.js canvas world.</p>
|
||
<p>Now, I’m not finished yet. I may be happy with my simple, elegant formula for angular acceleration, but I still have to apply it in code. This is an excellent opportunity to practice some object-oriented programming skills and create a <code>Pendulum</code> class. First, think about all the properties of a pendulum that I’ve mentioned:</p>
|
||
<ul>
|
||
<li>arm length</li>
|
||
<li>angle</li>
|
||
<li>angular velocity</li>
|
||
<li>angular acceleration</li>
|
||
</ul>
|
||
<p>The <code>Pendulum</code> class needs all these properties, too.</p>
|
||
<pre class="codesplit" data-code-language="javascript">class Pendulum {
|
||
constructor(){
|
||
// Length of arm
|
||
this.r = ????;
|
||
// Pendulum arm angle
|
||
this.angle = ????;
|
||
// Angular velocity
|
||
this.angleVelocity = ????;
|
||
// Angular acceleration
|
||
this.angleAcceleration = ????;
|
||
} </pre>
|
||
<p>Next, I need to write an <code>update()</code> method to update the pendulum’s angle according to the formula.</p>
|
||
<pre class="codesplit" data-code-language="javascript"> update() {
|
||
// Arbitrary constant
|
||
let gravity = 0.4;
|
||
// Calculate acceleration according to the formula.
|
||
this.angleAcceleration = -1 * gravity * sin(this.angle);
|
||
// Increment velocity.
|
||
this.angleVelocity += this.angleAcceleration;
|
||
//{!1} Increment angle.
|
||
this.angle += this.angleVelocity;
|
||
}</pre>
|
||
<p>Note that the acceleration calculation now includes a multiplication by –1. When the pendulum is to the right of its resting position, the angle is positive, and so the sine of the angle is also positive. However, gravity should “pull” the bob back toward the resting position. Conversely, when the pendulum is to the left of its resting position, the angle is negative, and so its sine is negative, too. In this case, the pulling force should be positive. Multiplying by –1 is necessary in both scenarios.</p>
|
||
<figure class="half-width-right">
|
||
<img src="images/03_oscillation/03_oscillation_13.png" alt="Figure 3.13: A diagram showing the bob position relative to the pivot in polar and Cartesian coordinates">
|
||
<figcaption>Figure 3.13: A diagram showing the bob position relative to the pivot in polar and Cartesian coordinates</figcaption>
|
||
</figure>
|
||
<p>Next, I need a <code>show()</code> method to draw the pendulum on the canvas. But where exactly should I draw it? How do I calculate the <span data-type="equation">x,y</span> (Cartesian!) coordinates for both the pendulum’s pivot point (let’s call it <code>pivot</code>) and bob position (let’s call it <code>bob</code>)? This may be getting a little tiresome, but the answer, yet again, is trigonometry, as shown in Figure 3.13.</p>
|
||
<p>First, I’ll need to add a <code>this.pivot</code> property to the constructor to specify where to draw the pendulum on the canvas.</p>
|
||
<pre class="codesplit" data-code-language="javascript">this.pivot = createVector(100, 10);</pre>
|
||
<p>I know the bob should be a set distance away from the pivot, as determined by the arm length. That’s my variable <code>r</code>, which I’ll set now:</p>
|
||
<pre class="codesplit" data-code-language="javascript">this.r = 125;</pre>
|
||
<p>I also know the bob’s current angle relative to the pivot: it’s stored in the variable <code>angle</code>. Between the arm length and the angle, what I have is a polar coordinate for the bob: <span data-type="equation">(r,\theta)</span>. What I really need is a Cartesian coordinate, but luckily I already know how to use sine and cosine to convert from polar to Cartesian. And so:</p>
|
||
<pre class="codesplit" data-code-language="javascript">this.bob = createVector(r * sin(this.angle), r * cos(this.angle));</pre>
|
||
<p>Notice that I’m using <code>sin(this.angle)</code> for the <span data-type="equation">x</span> value and <code>cos(this.angle)</code> for the <span data-type="equation">y</span>. This is the opposite of what I showed you in the “Polar vs. Cartesian Coordinates” section earlier in the chapter. The reason for this is that I’m now looking for the top angle of a right triangle pointing down, as depicted in Figure 3.13. This angle lives between the y-axis and the hypotenuse, instead of between the x-axis and the hypotenuse, as you saw earlier in Figure 3.8.</p>
|
||
<p>Right now, the value of <code>this.bob</code> is assuming that the pivot is at point (0, 0). To get the bob’s position relative to wherever the pivot <em>actually</em> happens to be, I can just add <code>pivot</code> to the <code>bob</code> vector:</p>
|
||
<pre class="codesplit" data-code-language="javascript">this.bob.add(this.pivot);</pre>
|
||
<p>Now all that remains is the little matter of drawing a line and circle (you should be more creative, of course).</p>
|
||
<pre class="codesplit" data-code-language="javascript">stroke(0);
|
||
fill(127);
|
||
line(this.pivot.x, this.pivot.y, this.bob.x, this.bob.y);
|
||
circle(this.position.x, this.position.y, 16);</pre>
|
||
<p>Before I put everything together, there’s one last little detail I neglected to mention. Or really, lots of little details. Think about the pendulum arm for a moment. Is it a metal rod? A string? A rubber band? How is it attached to the pivot point? How long is it? What’s its mass? Is it a windy day? There are a lot of questions that I could continue to ask that would affect the simulation. I choose to live, however, in a fantasy world, one where the pendulum’s arm is some idealized rod that never bends and where the mass of the bob is concentrated in a single, infinitesimally small point.</p>
|
||
<p>Even though I prefer not to worry myself with all of these questions, there’s a critical missing piece here related to the calculation of angular acceleration. To keep things simple, in the derivation of the pendulum’s acceleration, I assumed that the length of the pendulum’s arm is 1. In reality, however, the length of the pendulum’s arm affects the acceleration of the pendulum due to the concepts of torque and moment of inertia. <strong><em>Torque</em></strong> is a measure of the rotational force acting on an object. In the case of a pendulum, torque is proportional to both the mass and the length of the arm (<span data-type="equation">M \times r</span>). The <strong><em>moment of inertia</em></strong> of a pendulum is a measure of how difficult it is to rotate the pendulum around the pivot point. It’s proportional to the square of the length of the arm (<span data-type="equation">r^2</span>).</p>
|
||
<p>By dividing the torque by the moment of inertia (<span data-type="equation">Mr / r^2 ⇒ M / r</span>), I can calculate the angular acceleration of the pendulum more accurately. In fact, I can continue to ignore mass, as it has no actual effect on the acceleration: it scales the force of gravity, which contributes to the force of the pendulum (<span data-type="equation">F_p)</span>, but it also divides the force of the pendulum (<span data-type="equation">A = F_p / M</span>) to calculate the acceleration. (This is the same reason different objects dropped from the Leaning Tower of Pisa fall at the same rate, as discussed in Chapter 2.) Therefore, setting aside mass, all that’s left is to divide by <code>r</code>. (For a more involved explanation, visit the <a href="http://calculuslab.deltacollege.edu/ODE/7-A-2/7-A-2-h.html">"Simple Pendulum" article</a> linked from the book’s website.)</p>
|
||
<pre class="codesplit" data-code-language="javascript">// Same formula as before but now dividing by r
|
||
this.angleAcceleration = (-1 * gravity * sin(this.angle)) / r;</pre>
|
||
<p>Finally, a real-world pendulum is going to experience some amount of friction (at the pivot point) and air resistance. As it stands, the pendulum would swing forever with the given code. To make it more realistic, I can slow the pendulum down with a "damping" trick. I say <em>trick</em> because rather than model the resistance forces with some degree of accuracy (as I did in Chapter 2), I can achieve a similar result simply by reducing the angular velocity by some arbitrary amount during each cycle. The following code reduces the velocity by 1 percent (or multiplies it by 0.99) each frame of animation:</p>
|
||
<pre class="codesplit" data-code-language="javascript">this.angleVelocity *= 0.99;</pre>
|
||
<p>Putting everything together, I have the following example (with the pendulum beginning at a 45-degree angle).</p>
|
||
<div data-type="example">
|
||
<h3 id="example-310-swinging-pendulum">Example 3.10: Swinging Pendulum</h3>
|
||
<figure>
|
||
<div data-type="embed" data-p5-editor="https://editor.p5js.org/natureofcode/sketches/MQZWruTlD" data-example-path="examples/03_oscillation/example_3_10_swinging_pendulum"><img src="examples/03_oscillation/example_3_10_swinging_pendulum/screenshot.png"></div>
|
||
<figcaption></figcaption>
|
||
</figure>
|
||
</div>
|
||
<pre class="codesplit" data-code-language="javascript">let pendulum;
|
||
|
||
function setup() {
|
||
createCanvas(640, 240);
|
||
//{!1} We make a new Pendulum object with an origin position and arm length.
|
||
pendulum = new Pendulum(width / 2, 10, 175);
|
||
}
|
||
|
||
function draw() {
|
||
background(255);
|
||
pendulum.update();
|
||
pendulum.show();
|
||
}</pre>
|
||
<pre class="codesplit" data-code-language="javascript">class Pendulum {
|
||
|
||
constructor(x, y, r) {
|
||
//{!8} Many, many variables to keep track of the Pendulum’s various properties
|
||
this.pivot = createVector(x, y); // Position of pivot
|
||
this.bob = createVector(); // Position of bob
|
||
this.r = r; // Length of arm
|
||
this.angle = PI / 4; // Pendulum arm angle
|
||
this.angleVelocity = 0; // Angle velocity
|
||
this.angleAcceleration = 0; // Angle acceleration
|
||
this.damping = 0.99; // Arbitrary damping
|
||
this.ballr = 24; // Arbitrary bob radius
|
||
}
|
||
|
||
update() {
|
||
let gravity = 0.4;
|
||
//{!1} Formula for angular acceleration
|
||
this.angleAcceleration = (-1 * gravity / this.r) * sin(this.angle);
|
||
|
||
//{!2} Standard angular motion algorithm
|
||
this.angleVelocity += this.angleAcceleration;
|
||
this.angle += this.angleVelocity;
|
||
|
||
// Apply some damping
|
||
this.angleVelocity *= this.damping;
|
||
}
|
||
|
||
show() {
|
||
//{!1} Applying polar to cartesian conversion. Instead of creating a new vector each time, I'll use set() to update the bob's position.
|
||
this.bob.set(this.r * sin(this.angle), this.r * cos(this.angle));
|
||
this.bob.add(this.pivot);
|
||
|
||
stroke(0);
|
||
//{!1} The arm
|
||
line(this.pivot.x, this.pivot.y, this.bob.x, this.bob.y);
|
||
fill(127);
|
||
//{!1} The bob
|
||
circle(this.bob.x, this.bob.y, this.ballr * 2);
|
||
}
|
||
}</pre>
|
||
<p>Note that the version of the example posted on the book’s website has additional code to allow the user to grab the pendulum and swing it with the mouse.</p>
|
||
<div data-type="exercise">
|
||
<h3 id="exercise-312">Exercise 3.12</h3>
|
||
<p>String together a series of pendulums so that the bob of one is the pivot point of another. Note that doing this may produce intriguing results but will be wildly inaccurate physically. Simulating an actual double pendulum involves sophisticated equations. You can read about them in the <a href="https://scienceworld.wolfram.com/physics/DoublePendulum.html">Wolfram Research article on double pendulums</a> or watch my video on coding a double pendulum (<a href="https://thecodingtrain.com/challenges/93-double-pendulum">Coding Train Challenge #93</a>).</p>
|
||
<figure>
|
||
<div data-type="embed" data-p5-editor="https://editor.p5js.org/natureofcode/sketches/Nlw45LpMN" data-example-path="examples/03_oscillation/exercise_3_12_double_pendulum"><img src="examples/03_oscillation/exercise_3_12_double_pendulum/screenshot.png"></div>
|
||
<figcaption></figcaption>
|
||
</figure>
|
||
</div>
|
||
<div data-type="exercise">
|
||
<h3 id="exercise-313">Exercise 3.13</h3>
|
||
<figure class="half-width-right">
|
||
<img src="images/03_oscillation/03_oscillation_14.png" alt=" ">
|
||
<figcaption> </figcaption>
|
||
</figure>
|
||
<p>Using trigonometry, how do you calculate the magnitude of the <strong><em>normal force</em></strong> depicted here (the force perpendicular to the incline on which the sled rests)? You can consider the magnitude of <span data-type="equation">F_\text{gravity}</span> to be a known constant. Look for a right triangle to help get you started. After all, the “normal” force is a component of the force of gravity. If it helps to draw over the diagram and make more right triangles, go for it!</p>
|
||
<figure>
|
||
<img src="images/03_oscillation/03_oscillation_15.png" alt="">
|
||
<figcaption></figcaption>
|
||
</figure>
|
||
</div>
|
||
<div data-type="exercise">
|
||
<h3 id="exercise-314">Exercise 3.14</h3>
|
||
<p>Create a simulation of a box sliding down an incline with friction. Note that the magnitude of the friction force is equal to the normal force, as discussed in the previous exercise.</p>
|
||
</div>
|
||
<h2 id="spring-forces">Spring Forces</h2>
|
||
<p>In the “Properties of Oscillation” section, I modeled simple harmonic motion by mapping a sine wave to a range of pixels on a canvas. <a href="#exercise-36">Exercise 3.6</a> asked you to use this technique to create a simulation of a bob hanging from a spring. While using the <code>sin()</code> function is a quick-and-dirty, one-line-of-code way to get such a result, it won’t do if what you really want is a bob hanging from a spring that responds to other forces in the environment (wind, gravity, and so on). To accomplish a simulation like that, you need to model the force of a spring using vectors. Overall, the system is quite similar to the pendulum example, only now the pendulum’s arm is a springy connection, and the fixed point is called an <em>anchor</em> rather than a <em>pivot</em> (see Figure 3.14).</p>
|
||
<figure>
|
||
<img src="images/03_oscillation/03_oscillation_16.png" alt="Figure 3.14: A spring with an anchor and bob.">
|
||
<figcaption>Figure 3.14: A spring with an anchor and bob.</figcaption>
|
||
</figure>
|
||
<p>The force of a spring is calculated according to Hooke’s law, named for Robert Hooke, a British physicist who developed the formula in 1660. Hooke originally stated the law in Latin: “<em>Ut tensio, sic vis</em>,” or “As the extension, so the force.” Think of it this way:</p>
|
||
<p><span class="highlight">The force of the spring is directly proportional to the extension of the spring.</span></p>
|
||
<figure class="half-width-right">
|
||
<img src="images/03_oscillation/03_oscillation_17.png" alt="Figure 3.15: A spring’s extension (x) is the difference between its current length and its rest length.">
|
||
<figcaption>Figure 3.15: A spring’s extension (<span data-type="equation">x</span>) is the difference between its current length and its rest length.</figcaption>
|
||
</figure>
|
||
<p>The extension is a measure of how much the spring has been stretched or compressed: as shown in Figure 3.15, it’s the difference between the current length of the spring and the spring’s resting length (its equilibrium state). Hooke’s law therefore says that if you pull on the bob a lot, the spring’s force will be strong, whereas if you pull on the bob a little, the force will be weak. Mathematically, the law is stated as follows:</p>
|
||
<div data-type="equation">F_{spring} = -kx</div>
|
||
<p>Here <span data-type="equation">k</span> is the “spring constant.” Its value scales the force, setting how elastic or rigid the spring is. Meanwhile, <span data-type="equation">x</span> is the extension, the current length minus the rest length.</p>
|
||
<p>Now remember, force is a vector, so you need to calculate both magnitude and direction. For the code, I‘ll start with the following three variables: two vectors for the anchor and bob positions, and one rest length.</p>
|
||
<pre class="codesplit" data-code-language="javascript">// Picking arbitrary values for the positions and rest length
|
||
let anchor = createVector(0, 0);
|
||
let bob = createVector(0, 120);
|
||
let restLength = 100;</pre>
|
||
<p>I’ll then use Hooke’s law to calculate the magnitude of the force. For that, I need <code>k</code> and <code>x</code>. Calculating <code>k</code> is easy; it’s just a constant, so I’ll make something up.</p>
|
||
<pre class="codesplit" data-code-language="javascript">let k = 0.1;</pre>
|
||
<p>Finding <code>x</code> is perhaps a bit more difficult. I need to know the “difference between the current length and the rest length.” The rest length is defined as the variable <code>restLength</code>. What’s the current length? The distance between the anchor and the bob. And how can I calculate that distance? How about the magnitude of a vector that points from the anchor to the bob? (Note that this is exactly the same process I employed to find the distance between objects for the purposes of calculating gravitational attraction in Chapter 2.)</p>
|
||
<pre class="codesplit" data-code-language="javascript">//{!1} A vector pointing from anchor to bob gives us the current length of the spring.
|
||
let dir = p5.Vector.sub(bob, anchor);
|
||
let currentLength = dir.mag();
|
||
let x = currentLength - restLength;</pre>
|
||
<p>Now that I’ve sorted out the elements necessary for the magnitude of the force (<span data-type="equation">-kx</span>), I need to figure out the direction, a unit vector pointing in the direction of the force. The good news is that I already have this vector. Right? Just a moment ago I asked the question “How I can calculate that distance?” and I answered “How about the magnitude of a vector that points from the anchor to the bob?” Well, that vector describes the direction of the force!</p>
|
||
<p>Figure 3.17 shows that if you stretch the spring beyond its rest length, there should be a force pulling it back towards the anchor. And if the spring shrinks below its rest length, the force should push it away from the anchor. The Hooke’s law formula accounts for this reversal of direction with the –1.</p>
|
||
<figure>
|
||
<img src="images/03_oscillation/03_oscillation_18.png" alt="Figure 3.17: The spring force points in the opposite direction of the displacement.">
|
||
<figcaption>Figure 3.17: The spring force points in the opposite direction of the displacement.</figcaption>
|
||
</figure>
|
||
<p>All I need to do now is set the magnitude of the vector used for the distance calculation. Let’s take a look at the code and rename that vector variable as <code>force</code>.</p>
|
||
<pre class="codesplit" data-code-language="javascript">//{!4} Magnitude of spring force according to Hooke’s law
|
||
let k = 0.1;
|
||
let force = p5.Vector.sub(bob, anchor);
|
||
let currentLength = force.mag();
|
||
let x = currentLength - restLength;
|
||
|
||
// Putting it together: direction and magnitude!
|
||
force.setMag(-1 * k * x);</pre>
|
||
<p>Now that I have the algorithm for computing the spring force, the question remains: what object-oriented programming structure should I use? This is one of those situations in which there’s no “correct” answer. There are several possibilities; which one I choose depends on my goals and personal coding style. Since I’ve been working all along with a <code>Mover</code> class, I’ll stick with this same framework. I’ll think of the <code>Mover</code> class as the spring’s “bob.” The bob needs <code>position</code>, <code>velocity</code>, and <code>acceleration</code> vectors to move about the canvas. Perfect—I’ve got that already! And perhaps the bob experiences a gravity force via the <code>applyForce()</code> method. This leaves just one more step: applying the spring force.</p>
|
||
<pre class="codesplit" data-code-language="javascript">let bob;
|
||
|
||
function setup() {
|
||
bob = new Bob();
|
||
}
|
||
|
||
function draw() {
|
||
//{!1} Chapter 2 “make-up-a-gravity force”
|
||
let gravity = createVector(0, 1);
|
||
bob.applyForce(gravity);
|
||
//{!2 .bold} I need to also calculate and apply a spring force!
|
||
let springForce = _______________????
|
||
bob.applyForce(springForce);
|
||
|
||
//{!2} The standard update() and display() functions
|
||
bob.update();
|
||
bob.display();
|
||
}</pre>
|
||
<p>One option would be to write all of the spring force code in the main <code>draw()</code> loop. But thinking ahead to when you might have multiple bob and spring connections, it would be wise to create an additional class, a <code>Spring</code> class. As shown in Figure 3.18, the <code>Bob</code> class keeps track of the movements of the bob; the <code>Spring</code> class keeps track of the spring’s anchor position, its rest length, and calculates the spring force on the bob.</p>
|
||
<figure class="Spring Bob">
|
||
<img src="images/03_oscillation/03_oscillation_19.png" alt="Figure 3.18: The class has anchor and rest length; the class has position, velocity, and acceleration.">
|
||
<figcaption>Figure 3.18: The class has anchor and rest length; the class has position, velocity, and acceleration.</figcaption>
|
||
</figure>
|
||
<p>This allows me to write a lovely sketch as follows:</p>
|
||
<pre class="codesplit" data-code-language="javascript">let bob;
|
||
//{!1 .bold} Adding a Spring object
|
||
let spring;
|
||
|
||
function setup() {
|
||
bob = new Bob();
|
||
spring = new Spring();
|
||
}
|
||
|
||
function draw() {
|
||
let gravity = createVector(0, 1);
|
||
bob.applyForce(gravity);
|
||
|
||
//{!1 .bold} This new function in the Spring class will take care of computing the force of the spring on the bob.
|
||
spring.connect(bob);
|
||
|
||
bob.update();
|
||
bob.display();
|
||
spring.display();
|
||
}</pre>
|
||
<p>Think about how this compares to my first stab at gravitational attraction in <a href="/force#example-26-attraction">Example 2.6</a>, when I had separate <code>Mover</code> and <code>Attractor</code> classes. There, I wrote something like:</p>
|
||
<pre class="codesplit" data-code-language="javascript"> let force = attractor.attract(mover);
|
||
mover.applyForce(force);</pre>
|
||
<p>The analogous situation here with a spring might have been:</p>
|
||
<pre class="codesplit" data-code-language="javascript"> let force = spring.connect(bob);
|
||
bob.applyForce(force);</pre>
|
||
<p>Instead, in this example I have:</p>
|
||
<pre class="codesplit" data-code-language="javascript"> spring.connect(bob);</pre>
|
||
<p>What gives? Why don’t I need to call <code>applyForce()</code> on the bob? The answer, of course, is that I <em>do</em> need to call <code>applyForce()</code> on the bob. It’s just that instead of doing it in <code>draw()</code>, I’m demonstrating that a perfectly reasonable (and sometimes preferable) alternative is to ask the <code>connect()</code> method to call <code>applyForce()</code> on the bob internally.</p>
|
||
<pre class="codesplit" data-code-language="javascript"> connect(bob) {
|
||
let force = some fancy calculations
|
||
|
||
//{!1} The function connect() takes care of calling applyForce() and therefore doesn’t have to return a vector to the calling area.
|
||
bob.applyForce(force);
|
||
}</pre>
|
||
<p>Why do it one way with the <code>Attractor</code> class and another way with the <code>Spring</code> class? When I first discussed forces, it was a bit clearer to show all the forces being applied in the <code>draw()</code> loop, and hopefully this helped you learn about force accumulation. Now that you’re more comfortable, perhaps it’s simpler to embed some of the details inside the objects themselves.</p>
|
||
<p>Let’s take a look at the rest of the elements in the <code>Spring</code> class.</p>
|
||
<div data-type="example">
|
||
<h3 id="example-311-a-spring-connection">Example 3.11: A Spring connection</h3>
|
||
<figure>
|
||
<div data-type="embed" data-p5-editor="https://editor.p5js.org/natureofcode/sketches/HZOUeCe9p" data-example-path="examples/03_oscillation/example_3_11_a_spring_connection"><img src="examples/03_oscillation/example_3_11_a_spring_connection/screenshot.png"></div>
|
||
<figcaption></figcaption>
|
||
</figure>
|
||
</div>
|
||
<pre class="codesplit" data-code-language="javascript">class Spring {
|
||
|
||
//{!1} The constructor initializes the anchor point and rest length.
|
||
constructor(x, y, length) {
|
||
//{!1} The spring’s anchor position.
|
||
this.anchor = createVector(x, y);
|
||
//{!2} Rest length and spring constant variables
|
||
this.restLength = length;
|
||
this.k = 0.1;
|
||
}
|
||
|
||
//{!1} Calculate spring force as implementation of Hooke’s Law.
|
||
connect(bob) {
|
||
//{!1 .bold .code-wide} Get a vector pointing from anchor to Bob position.
|
||
let force = p5.Vector.sub(bob.position, this.anchor);
|
||
//{!2 .bold} Calculate the displacement between distance and rest length. I'll use the variable name "stretch" instead of "x" to be more descriptive.
|
||
let currentLength = force.mag();
|
||
let stretch = currentLength - this.restLength;
|
||
|
||
//{!2 .bold} Direction and magnitude together!
|
||
force.setMag(-1 * this.k * stretch);
|
||
|
||
//{!1} Call applyForce() right here!
|
||
bob.applyForce(force);
|
||
}
|
||
|
||
//{!5} Draw the anchor.
|
||
show() {
|
||
fill(127);
|
||
circle(this.anchor.x, this.anchor.y, 10);
|
||
}
|
||
|
||
//{!4} Draw the spring connection between Bob position and anchor.
|
||
showLine(bob) {
|
||
stroke(0);
|
||
line(bob.position.x, bob.position.y, this.anchor.x, this.anchor.y);
|
||
}
|
||
}</pre>
|
||
<p>The complete code for this example is available on the book’s website and incorporates two additional features: (1) the <code>Bob</code> class includes methods for mouse interactivity, allowing you to drag the bob around the window, and (2) the <code>Spring</code> class includes a method to constrain the connection’s length between a minimum and a maximum value.</p>
|
||
<div data-type="exercise">
|
||
<h3 id="exercise-315">Exercise 3.15</h3>
|
||
<p>Before running to see the example online, take a look at this <code>constrainLength</code> method and see if you can fill in the blanks.</p>
|
||
<pre class="codesplit" data-code-language="javascript">constrainLength(bob, minlen, maxlen) {
|
||
//{!1} Vector pointing from Bob to Anchor
|
||
let direction = p5.Vector.sub(<span class="blank">bob.position</span>, <span class="blank">this.anchor</span>);
|
||
let length = direction.mag();
|
||
|
||
//{!1} Is it too short?
|
||
if (length < minlen) {
|
||
direction.setMag(<span class="blank">minlen</span>);
|
||
//{!1} Keep position within constraint.
|
||
bob.position = p5.Vector.add(<span class="blank">this.anchor</span>, <span class="blank">direction</span>);
|
||
bob.velocity.mult(0);
|
||
//{!1} Is it too long?
|
||
} else if (length<span class="blank"> > maxlen</span>) {
|
||
direction.setMag(<span class="blank">maxlen</span>);
|
||
//{!1} Keep position within constraint.
|
||
bob.position = p5.Vector.add(<span class="blank">this.anchor</span>, <span class="blank">direction</span>);
|
||
bob.velocity.mult(0);
|
||
}
|
||
}</pre>
|
||
</div>
|
||
<div data-type="exercise">
|
||
<h3 id="exercise-316">Exercise 3.16</h3>
|
||
<p>Create a system of multiple bobs and spring connections. How about connecting a bob to another bob with no fixed anchor?</p>
|
||
</div>
|
||
<div data-type="project">
|
||
<h3 id="the-ecosystem-project-2">The Ecosystem Project</h3>
|
||
<p>Step 3 Exercise:</p>
|
||
<p>Take one of your creatures and incorporate oscillation into its motion. You can use the <code>Oscillator</code> class from Example 3.7 as a model. The <code>Oscillator</code> object, however, oscillates around a single point (the middle of the window). Try oscillating around a moving point. In other words, design a creature that moves around the screen according to position, velocity, and acceleration. But that creature isn’t just a static shape, it’s an oscillating body. Consider tying the speed of oscillation to the speed of motion. Think of a butterfly’s flapping wings or the legs of an insect. Can you make it appear that the creature’s internal mechanics (oscillation) drive its locomotion? For a sample, check out the “AttractionArrayWithOscillation” example with the code download.</p>
|
||
</div>
|
||
</section> |