In the final example of Chapter 1, I demonstrated how to calculate a dynamic acceleration based on a vector pointing from a circle on the canvas to the mouse position. The resulting motion resembled a magnetic attraction between shape and mouse, as if some force was pulling the circle in toward the mouse. In this chapter, I’ll detail the concept of a force and its relationship to acceleration. The goal, by the end of this chapter, is to build a simple physics engine and understand how objects move around a canvas responding to a variety of environmental forces.
-A physics engine is a computer program (or code library) that simulates the behavior of objects in a physical environment. In our case, the objects are two-dimensional shapes, and the environment is a rectangular canvas. Physics engines can be developed to be highly precise (requiring high-performance computing) or real-time (using simple and fast algorithms).
+Let’s begin by taking a conceptual look at what it means to be a force in the real world. Just like the word “vector,” the term “force” can have a variety of meanings. It can indicate a powerful physical intensity, as in “They pushed the boulder with great force,” or a powerful influence, as in “They’re a force to be reckoned with!” The definition of force that I’m interested in for this chapter is more formal and comes from Sir Isaac Newton’s three laws of motion:
A force is a vector that causes an object with mass to accelerate.
diff --git a/content/03_oscillation.html b/content/03_oscillation.html index b6b3357..4b69e5f 100644 --- a/content/03_oscillation.html +++ b/content/03_oscillation.html @@ -7,7 +7,7 @@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: oscillation, 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.
Trigonometry 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.
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.
-Before going any further, I need to make sure you understand what it means to be an angle in p5.js. If you have experience with p5.js, you’ve undoubtedly encountered this issue while using the rotate()
function to rotate and spin objects.
You’re most likely to be familiar with the concept of an angle as measured in degrees (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.
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 my Coding Train video series on transformations in p5.js or reading Gene Kogan’s transformation tutorial at genekogan.com.
+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 my Coding Train video series on transformations in p5.js.
Rotate a baton-like object (see below) around its center using translate()
and rotate()
.
Another term for rotation is angular motion—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—angular motion can be described in terms of angular velocity—that rate at which an object’s angle changes. By extension, angular acceleration describes changes in an object’s angular velocity.
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
Adding in the principles of angular motion, I can instead write the following example (the solution to Exercise 3.1).
// Position let angle = 0; // Velocity -let aVelocity = 0; +let angleVelocity = 0; //{!1} Acceleration -let aAcceleration = 0.0001; +let angleAcceleration = 0.0001; function setup() { createCanvas(640, 240); @@ -94,18 +96,17 @@ function draw() { circle(-60, 0, 16); // Angular equivalent of velocity.add(acceleration); - aVelocity += aAcceleration; + angleVelocity += angleAcceleration; //{!1} Angular equivalent of position.add(velocity); - angle += aVelocity; + angle += angleVelocity; }-
Instead of incrementing angle
by a fixed amount to steadily rotate the baton, every frame I add aAcceleration
to aVelocity
, then add aVelocity
to angle
. As a result, the baton starts with no rotation, and then spins faster and faster as the angular velocity accelerates.
Instead of incrementing angle
by a fixed amount to steadily rotate the baton, every frame I add angleAcceleration
to angleVelocity
, then add angleVelocity
to angle
. As a result, the baton starts with no rotation, and then spins faster and faster as the angular velocity accelerates.
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?
The logical next step is to incorporate this idea of angular motion into the Mover
class. First, I need to add some variables to the class’s constructor.
class Mover { - constructor(){ this.position = createVector(); this.velocity = createVector(); @@ -114,8 +115,8 @@ function draw() { //{!3} Variables for angular motion this.angle = 0; - this.aVelocity = 0; - this.aAcceleration = 0; + this.angleVelocity = 0; + this.angleAcceleration = 0; } }@@ -126,8 +127,8 @@ function draw() { this.position.add(this.velocity); //{!2} Newfangled angular motion - this.aVelocity += this.aAcceleration; - this.angle += this.aVelocity; + this.angleVelocity += this.angleAcceleration; + this.angle += this.angleVelocity; this.acceleration.mult(0); } @@ -147,11 +148,11 @@ function draw() { //{!1} pop() restores the previous state after rotation is complete pop(); } -
At this point, if you were to actually go ahead and create a Mover
object, you wouldn’t see it behave any differently. This is because the angular acceleration is initialized to zero (this.aAcceleration = 0;
) . For the object to rotate, it needs a non-zero acceleration! Certainly, one option is to hard-code a number in the constructor:
this.aAcceleration = 0.01;+
At this point, if you were to actually go ahead and create a Mover
object, you wouldn’t see it behave any differently. This is because the angular acceleration is initialized to zero (this.angleAcceleration = 0;
) . For the object to rotate, it needs a non-zero acceleration! Certainly, one option is to hard-code a number in the constructor:
this.angleAcceleration = 0.01;
You can produce a more interesting result, however, by dynamically assigning an angular acceleration in the update()
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 torque and moment of inertia, 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:
// Using the x component of the object's linear acceleration to calculate angular acceleration - this.aAcceleration = this.acceleration.x;+ this.angleAcceleration = this.acceleration.x;
Yes, this is arbitrary, but it does do something. 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 x
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.
Dividing the x
component by some value, or perhaps constraining the angular velocity to a reasonable range, could really help. Here’s the entire update()
function with these tweaks added.
update() { - this.velocity.add(this.acceleration); this.position.add(this.velocity); //{!1} Calculate angular acceleration according to acceleration’s x component. - this.aAcceleration = this.acceleration.x / 10.0; - this.aVelocity += this.aAcceleration; + 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.aVelocity = constrain(this.aVelocity, -0.1, 0.1); - this.angle += this.aVelocity; + this.angleVelocity = constrain(this.angleVelocity, -0.1, 0.1); + this.angle += this.angleVelocity; this.acceleration.mult(0); }-
Notice that I’ve used multiple strategies to keep the object from spinning out of control. First, I divide acceleration.x
by 10
before assigning it to aAcceleration
. Then, for good measure, I also use constrain()
to confine aVelocity
to the range (-0.1, 0.1)
.
Notice that I’ve used multiple strategies to keep the object from spinning out of control. First, I divide acceleration.x
by 10
before assigning it to angleAcceleration
. Then, for good measure, I also use constrain()
to confine angleVelocity
to the range (-0.1, 0.1)
.
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).
@@ -367,19 +367,19 @@ function draw() {Take a look at the graph of the sine function in Figure 3.9, where y = \sin(x).
The output of the sine function is a smooth curve alternating between −1 and 1, also known as a sine wave. This behavior, a periodic movement between two points, is the oscillation 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.
-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.
+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.
-This pattern of oscillating back and forth around a central point is known as simple harmonic motion (or, to be fancier, “the periodic sinusoidal oscillation of an object”). The code to achieve this is remarkably simple, but before I get into it, I’d like to introduce some of the key terminology related to oscillation (and waves).
+This pattern of oscillating back and forth around a central point is known as simple harmonic motion (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).
Simple harmonic motion can be expressed as any position (in this case, the x position) as a function of time, with the following two elements:
Once I have the amplitude and period, it’s time to write a formula to calculate the circle’s x position as a function of time (the current frame count):
// amplitude and period are my own variables, frameCount is built into p5.js let x = amplitude * sin(TWO_PI * frameCount / period);-
Think about what’s going here. First, whatever value the sin()
function returns is multiplied by amplitude
. As you saw in Figure 3.9, the output of the sine function oscillates between -1 and 1. Multiplying that value by my chosen amplitude a gives me the desired result: a value that oscillates between -a and a. (This is also a place where you could use p5.js’s map()
function to map the output of sin()
to a custom range.)
Think about what’s going here. First, whatever value the sin()
function returns is multiplied by amplitude
. As you saw in Figure 3.9, the output of the sine function oscillates between -1 and 1. Multiplying that value by my chosen amplitude—call it a—gives me the desired result: a value that oscillates between -a and a. (This is also a place where you could use p5.js’s map()
function to map the output of sin()
to a custom range.)
Now, think about what’s inside the sin()
function:
TWO_PI * frameCount / period-
What’s going on here? Start with what you know. I‘ve explained that sine has a period of 2\pi, meaning it will start at 0
and repeat at 2\pi, 4\pi, 6\pi, and so on. If my desired period of oscillation is 120 frames, then I want the circle to be in the same position when frameCount
is at 120 frames, 240 frames, 360 frames, and so on. Here, frameCount
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 frameCount
increases.
What’s going on here? Start with what you know. I‘ve explained that sine has a period of 2\pi, meaning it will start at 0 and repeat at 2\pi, 4\pi, 6\pi, and so on. If my desired period of oscillation is 120 frames, then I want the circle to be in the same position when frameCount
is at 120 frames, 240 frames, 360 frames, and so on. Here, frameCount
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 frameCount
increases.
etc. | -- | + | etc. | +etc. |
Before moving on, I would be remiss not to mention frequency, 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 frequency = 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.
+Before moving on, I would be remiss not to mention frequency, 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.
Now I‘ll rewrite it a slightly different way:
let x = amplitude * sin ( some value that increments slowly );
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 sin()
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 2\pi, the object will have completed one cycle of oscillation.
The technique here mirrors what I did with Perlin noise in the Introduction. With noise, I incremented an “offset” variable (which I called t
or xoff
) to sample different outputs from the noise()
function, creating a smooth transition of values. Now, I’m going to increment a value (I’ll call it angle
) that's fed into the sin()
function. The difference is that the output from sin()
is a smoothly repeating sine wave, without any randomness.
The technique here mirrors what I did with Perlin noise in the Introduction. In that case, I incremented an “offset” variable (which I called t
or xoff
) to sample different outputs from the noise()
function, creating a smooth transition of values. Now, I’m going to increment a value (I’ll call it angle
) that's fed into the sin()
function. The difference is that the output from sin()
is a smoothly repeating sine wave, without any randomness.
You might be wondering why I refer to the incrementing value as angle
given that there’s no visible rotation of the object itself. The term angle is used because the value is passed into the sin()
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 x
position in terms of a changing angle. I’ll assume these global variables:
let angle = 0; let angleVelocity = 0.05;@@ -485,7 +485,7 @@ let angleVelocity = 0.05; angle += angleVelocity; let x = amplitude * sin(angle); } -
Here angle
is my “some value that increments slowly,” and the amount it slowly increments by is aVelocity
.
Here angle
is my “some value that increments slowly,” and the amount it slowly increments by is angleVelocity
.
class Oscillator { - constructor() { //{!3} Using a p5.Vector to track two angles! this.angle = createVector(); @@ -557,11 +556,11 @@ function draw() { pop(); } }-
To better understand the Oscillator
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 angle, angular velocity, and amplitude.
To better understand the Oscillator
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.
The key is to recognize that the x
and y
properties of the p5.Vector
objects this.angle
, this.angleVelocity
, and this.amplitude
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 x
and y
are calculated in the show()
method, mapping the oscillations onto the positions of the object.
Try initializing each Oscillator
object with velocities and amplitudes that are not random to create some sort of regular pattern. Can you make the oscillators appear to be the legs of an insect-like creature?
Try initializing each Oscillator
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?
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.
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.
-I’ll go with the simpler case, angular velocity. I know I need three variables: an angle, an angular velocity, and an amplitude:
+I’ll go with the simpler case, angular velocity. I know I need three variables: an angle, an angular velocity, and an amplitude.
let angle = 0; let angleVelocity = 0.2; let amplitude = 100;
Then I’m going to loop through all of the x
values for each point on the wave. For now, I’ll put 24 pixels between adjacent x
values. For each x
, I’ll follow these three steps:
What happens if you try different values for angleVelocity
?
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.
-Notice that everything in Example 3.8 happens inside setup()
, 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 everything from beginShape()
to endShape()
inside the draw()
function and let angle
continue incrementing from one cycle to the next.”
Notice that everything in Example 3.8 happens inside setup()
, 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 for
loop inside the draw()
function and let angle
continue incrementing from one cycle to the next.”
Note for Nathan
-That’s a nice thought, but it doesn’t work. If you look at the wave in Example 3.8, the right edge doesn’t match the left edge; where it ends in one cycle of draw()
can’t be where it starts in the next. Instead, what you need is a variable dedicated entirely to tracking the starting angle
value in each frame of the animation. This variable (which I’ll call startAngle
) increments at its own pace, controlling how much the wave progresses from one frame to the next.
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 draw()
can’t be where it starts in the next. Instead, what you need is a variable dedicated entirely to tracking the starting angle
value in each frame of the animation. This variable (which I’ll call startAngle
) increments at its own pace, controlling how much the wave progresses from one frame to the next.
In this code example, the increment of startAngle
is hardcoded to be 0.02
. Instead, you may want to consider reusing angleVelocity
or creating a second variable. By reusing angleVelocity
, the progression of the wave would be tied to the oscillation, possibly creating a more synchronized movement. Introducing a separate variable, perhaps called startAngleVelocity
, would allow independent control of the speed of the wave.
In this code example, the increment of startAngle
is hardcoded to be 0.02
, but you may want to consider reusing angleVelocity
or creating a second variable instead. By reusing angleVelocity
, the progression of the wave would be tied to the oscillation, possibly creating a more synchronized movement. Introducing a separate variable, perhaps called startAngleVelocity
, would allow independent control of the speed of the wave.
Try using the Perlin noise function instead of sine or cosine to set the y
values in Example 3.9.
Encapsulate the wave-generating code into a Wave
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 beginShape()
endShape()
and vertex()
?
Encapsulate the wave-generating code into a Wave
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 beginShape()
, endShape()
, and vertex()
?
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.
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 angular acceleration and velocity, the change of the arm’s angle \theta 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.
-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 tension and introduces a second force, the force of the pendulum itself, that points toward the pendulum’s resting position, perpendicular to the arm. Together, these two forces make the pendulum swing back and forth.
-To actually calculate my 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 pendulum forces, as shown in Figure 3.12.
+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 F_p (see Figure 3.12) points toward the pendulum’s resting position, perpendicular to the arm. Together, this net pendulum force, the result of gravity and tension, causes the pendulum swing back and forth.
+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.
The force of the pendulum (F_p) and the force of gravity (F_g) originate from the same point, the center of the bob. F_p is perpendicular to the arm of the pendulum, pointing in the direction of the resting position, and F_g points straight down. Draw an extta 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 \theta 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 \theta. Since sine equals opposite over hypotenuse, you then have:
+The force of the pendulum (F_p) and the force of gravity (F_g) originate from the same point, the center of the bob. F_p is perpendicular to the arm of the pendulum, pointing in the direction of the resting position, and F_g 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 \theta 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 \theta. Since sine equals opposite over hypotenuse, you then have:
Or, thinking in terms of the force of the pendulum:
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 gravity
) as a variable that scales the acceleration.
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 that involve force-induced rotation, no matter how you choose to design your p5.js canvas world.
+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.
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 Pendulum
class. First, think about all the properties of a pendulum that I’ve mentioned:
The Pendulum
class needs all these properties, too.
class Pendulum { - constructor(){ // Length of arm this.r = ????; @@ -761,13 +753,13 @@ function draw() {Figure 3.13: A diagram showing the bob position relative to the pivot in polar and Cartesian coordinates
Next, I need a show()
method to draw the pendulum on the canvas. But where exactly should I draw it? How do I calculate the x,y (Cartesian!) coordinates for both the pendulum’s pivot point (let’s call it pivot
) and bob position (let’s call it bob
)? This may be getting a little tiresome, but the answer, yet again, is trigonometry, as shown in Figure 3.13.
First, I’ll need to add a this.pivot
property to the constructor to specify to draw the pendulum on the canvas.
First, I’ll need to add a this.pivot
property to the constructor to specify where to draw the pendulum on the canvas.
this.pivot = createVector(100, 10);
I know the bob should be a set distance away from the pivot, as determined by the arm length. That’s my variable r
, which I’ll set now:
this.r = 125;-
I also know the bob’s current angle relative to the pivot: it’s stored in the variable angle
. Between the arm length and the angle, what I have is a polar coordinate for the bob relative to the origin: (r,\theta). 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:
I also know the bob’s current angle relative to the pivot: it’s stored in the variable angle
. Between the arm length and the angle, what I have is a polar coordinate for the bob: (r,\theta). 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:
this.bob = createVector(r * sin(this.angle), r * cos(this.angle));-
Notice that I’m using sin(this.angle)
for the x value and cos(this.angle)
for the y. 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, rather than the bottom angle of a right triangle pointing up, as you saw earlier in Figure 3.8.
Notice that I’m using sin(this.angle)
for the x value and cos(this.angle)
for the y. 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 the angle between the x-axis and the hypotenuse, as you saw earlier in Figure 3.8.
Right now, the value of this.bob
is assuming that the pivot is at point (0, 0). To get the bob’s position relative to wherever the pivot actually happens to be, I can just add pivot
to the bob
vector:
this.bob.add(this.pivot);
Now all that remains is the little matter of drawing a line and circle (you should be more creative, of course).
@@ -776,8 +768,8 @@ fill(127); line(this.pivot.x, this.pivot.y, this.bob.x, this.bob.y); circle(this.position.x, this.position.y, 16);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.
-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. Torque 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 (m \times r). The moment of inertia 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 (r^2).
-By dividing the torque by the moment of inertia (mr / r^2 ⇒ m / r), I can calculate the angular acceleration of the pendulum more accurately. Remember, mass, while scaling F_p itself doesn’t change the acceleration since A = F_p / M. So all that’s left is to divide by r
. (For a more involved explanation, visit The Simple Pendulum website.)
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. Torque 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 (M \times r). The moment of inertia 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 (r^2).
+By dividing the torque by the moment of inertia (Mr / r^2 ⇒ M / r), 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 (F_p), but it also divides the force of the pendulum (A = F_p / M) 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 r
. (For a more involved explanation, visit The Simple Pendulum website.)
// Same formula as before but now dividing by r this.angleAcceleration = (-1 * gravity * sin(this.angle)) / r;
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 trick 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:
@@ -820,10 +812,10 @@ function draw() { update() { let gravity = 0.4; //{!1 .code-wide} Formulafor angular acceleration - this.aAcceleration = (-1 * gravity / this.r) * sin(this.angle); + this.angleAcceleration = (-1 * gravity / this.r) * sin(this.angle); //{!2} Standard angular motion algorithm - this.aVelocity += this.angleAcceleration; + this.angleVelocity += this.angleAcceleration; this.angle += this.angleVelocity; // Apply some damping @@ -859,7 +851,7 @@ function draw() {Using trigonometry, how do you calculate the magnitude of the normal force depicted here (the force perpendicular to the incline on which the sled rests)? Note that, as indicated, the “normal” force is a component of the force of gravity. [NOTE: Add some tips about drawing over the diagram, looking for the right angle]
+Using trigonometry, how do you calculate the magnitude of the normal force depicted here (the force perpendicular to the incline on which the sled rests)? You can consider the magnitude of F_\text{gravity} 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!
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.
In the “Oscillation Amplitude and Period” section, I modeled simple harmonic motion by mapping a sine wave to a rangle o pixels on a canvas. Exercise 3.6 asked you to use this technique to create a simulation of a bob hanging from a spring. While using the sin()
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 anchor rather than a pivot (see Figure 3.14).
In the “Properties of Oscillation” section, I modeled simple harmonic motion by mapping a sine wave to a range of pixels on a canvas. Exercise 3.6 asked you to use this technique to create a simulation of a bob hanging from a spring. While using the sin()
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 anchor rather than a pivot (see Figure 3.14).
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:
Here k is the “spring constant.” Its value scales the force, setting how elastic or rigid the spring is. Meanwhile, x is the extension, the current length minus the rest length.
-Now remember, force is a vector, so you need to calculate both magnitude and direction. Let’s look at one more diagram of the spring and label all the givens we might have in a p5.js sketch.
-For the code, I‘ll start with the following three variables as shown in Figure 3.16.
-let anchor = createVector(); -let bob = createVector(); -let restLength = ????;+
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.
+// Picking arbitrary values for the positions and rest length +let anchor = createVector(0, 0); +let bob = createVector(0, 120); +let restLength = 100;
I’ll then use Hooke’s law to calculate the magnitude of the force. For that, I need k
and x
. Calculating k
is easy; it’s just a constant, so I’ll make something up.
let k = 0.1;
Finding x
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 restLength
. 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.)
Now that I’ve sorted out the elements necessary for the magnitude of the force (-kx), 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!
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.
All I need to do now is set the magnitude of the vector used used for the distance calculation. Let’s take a look at the code and rename that vector variable as force
.
One option would be to write all of the spring force code in the main draw()
loop. But thinking ahead to when you might have multiple bob and spring connections, it would be wise to create an additional class, a Spring
class. As shown in Figure 3.18, the Bob
class keeps track of the movements of the bob; the Spring
class keeps track of the spring’s anchor position, its rest length, and calculates the spring force on the bob.
This allows me to write a lovely sketch as follows:
@@ -991,22 +980,20 @@ function draw() { //{!1} The spring’s anchor position. this.anchor = createVector(x, y); //{!2} Rest length and spring constant variables - this.length = length; + this.restLength = length; this.k = 0.1; } - //{!1} Calculate spring force—our implementation of Hooke’s Law. + //{!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. - let d = force.mag(); - let stretch = d - this.length; + //{!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.normalize(); - force.mult(-1 * this.k * stretch); + force.setMag(-1 * this.k * stretch); //{!1} Call applyForce() right here! bob.applyForce(force); @@ -1019,9 +1006,9 @@ function draw() { } //{!4} Draw the spring connection between Bob position and anchor. - showLine(b) { - stroke(255); - line(b.position.x, b.position.y, this.anchor.x, this.anchor.y); + showLine(bob) { + stroke(0); + line(bob.position.x, bob.position.y, this.anchor.x, this.anchor.y); } }The complete code for this example is available on the book’s website and incorporates two additional features: (1) the Bob
class includes methods for mouse interactivity, allowing you to drag the bob around the window, and (2) the Spring
class includes a method to constrain the connection’s length between a minimum and a maximum value.