How Do You Know Mass and Acceleration Are Inversely Proportional

Chapter 2. Forces

"Don't underestimate the Force." — Darth Vader

In the final case of Affiliate i, we saw how we could calculate a dynamic acceleration based on a vector pointing from a circle on the screen to the mouse location. The resulting move resembled a magnetic attraction between circle and mouse, equally if some strength were pulling the circle in towards the mouse. In this chapter nosotros will formalize our understanding of the concept of a forcefulness and its human relationship to acceleration. Our goal, past the end of this affiliate, is to understand how to make multiple objects move around the screen and respond to a variety of ecology forces.

2.1 Forces and Newton'due south Laws of Movement

Earlier we begin examining the practical realities of simulating forces in code, allow'southward have a conceptual look at what it means to exist a strength in the existent globe. Just like the discussion "vector," "force" is frequently used to mean a diversity of things. It can indicate a powerful intensity, as in "She pushed the boulder with bang-up forcefulness" or "He spoke forcefully." The definition of force that we care about is much more formal and comes from Isaac Newton's laws of motility:

A strength is a vector that causes an object with mass to accelerate.

The practiced news here is that we recognize the commencement role of the definition: a force is a vector. Thank goodness we but spent a whole chapter learning what a vector is and how to program with PVectors!

Let's wait at Newton's three laws of move in relation to the concept of a strength.

Newton's First Law

Newton'due south starting time law is normally stated every bit:

An object at residuum stays at residuum and an object in move stays in motion.

All the same, this is missing an important element related to forces. Nosotros could expand it by stating:

An object at remainder stays at rest and an object in motion stays in motion at a constant speed and direction unless acted upon by an unbalanced force.

By the time Newton came forth, the prevailing theory of motion—formulated by Aristotle—was nearly two thousand years sometime. Information technology stated that if an object is moving, some sort of force is required to keep information technology moving. Unless that moving thing is being pushed or pulled, it will simply tiresome down or stop. Right?

This, of course, is not truthful. In the absenteeism of any forces, no force is required to keep an object moving. An object (such as a ball) tossed in the globe's atmosphere slows downwards because of air resistance (a force). An object'due south velocity will only remain abiding in the absence of any forces or if the forces that act on it cancel each other out, i.e. the internet force adds upwardly to zero. This is oftentimes referred to as equilibrium . The falling brawl volition achieve a terminal velocity (that stays abiding) once the force of air resistance equals the strength of gravity.

Nature of Code Image

Figure ii.i: The pendulum doesn't move because all the forces cancel each other out (add up to a net strength of cypher).

In our Processing world, nosotros could restate Newton's showtime law as follows:

An object's PVector velocity volition remain constant if it is in a country of equilibrium.

Skipping Newton's 2nd law (arguably the virtually important law for our purposes) for a moment, let'south move on to the tertiary law.

Newton'south 3rd Law

This police force is often stated equally:

For every action there is an equal and opposite reaction.

This constabulary frequently causes some confusion in the fashion that it is stated. For 1, information technology sounds similar one force causes some other. Yes, if you push someone, that someone may actively decide to button y'all dorsum. But this is not the activeness and reaction we are talking about with Newton's third law.

Let's say y'all push confronting a wall. The wall doesn't actively decide to push dorsum on yous. There is no "origin" force. Your push simply includes both forces, referred to as an "activeness/reaction pair."

A meliorate way of stating the law might be:

Forces always occur in pairs. The two forces are of equal force, merely in opposite directions.

Now, this still causes confusion considering it sounds like these forces would e'er cancel each other out. This is not the case. Remember, the forces deed on different objects. And merely because the ii forces are equal, information technology doesn't mean that the movements are equal (or that the objects will finish moving).

Try pushing on a stationary truck. Although the truck is far more powerful than you lot, unlike a moving one, a stationary truck will never overpower you lot and send you flight backwards. The strength yous exert on it is equal and contrary to the strength exerted on your hands. The outcome depends on a variety of other factors. If the truck is a small truck on an icy downhill, you lot'll probably be able to get it to movement. On the other manus, if it's a very big truck on a dirt road and you push button hard enough (maybe fifty-fifty take a running start), you lot could injure your hand.

And if you are wearing roller skates when y'all push on that truck?

Nature of Code Image

Effigy two.2

You'll advance away from the truck, sliding along the road while the truck stays put. Why practise you slide but not the truck? For one, the truck has a much larger mass (which we'll become into with Newton'south second constabulary). At that place are other forces at work too, namely the friction of the truck's tires and your roller skates confronting the route.

Newton's Third Law (as seen through the eyes of Processing)

If we calculate a PVector f that is a force of object A on object B, we must also apply the forcefulness—PVector.mult(f,-1);—that B exerts on object A.

We'll run across that in the earth of Processing programming, we don't always have to stay true to the above. Sometimes, such as in the instance of see gravitational attraction between bodies, nosotros'll desire to model equal and opposite forces. Other times, such every bit when we're simply saying, "Hey, there's some wind in the environment," nosotros're not going to carp to model the strength that a body exerts dorsum on the air. In fact, we're not modeling the air at all! Call up, we are simply taking inspiration from the physics of the natural world, not simulating everything with perfect precision.

2.two Forces and Processing—Newton's Second Law every bit a Function

And here we are at the most important law for the Processing programmer.

Newton's 2d Law

This police force is stated as:

Strength equals mass times dispatch.

Or:

Why is this the near of import law for us? Well, allow'south write it a different way.

Acceleration is directly proportional to force and inversely proportional to mass. This means that if you go pushed, the harder you are pushed, the faster you lot'll move (accelerate). The bigger yous are, the slower you'll movement.

Weight vs. Mass
  • The mass of an object is a measure out of the amount of thing in the object (measured in kilograms).

  • Weight , though oft mistaken for mass, is technically the force of gravity on an object. From Newton's second law, we tin calculate it every bit mass times the acceleration of gravity (w = m * k). Weight is measured in newtons.

  • Density is divers as the amount of mass per unit of book (grams per cubic centimeter, for example).

Note that an object that has a mass of one kilogram on globe would accept a mass of one kilogram on the moon. However, information technology would weigh only one-6th as much.

At present, in the world of Processing, what is mass anyway? Aren't nosotros dealing with pixels? To start in a simpler place, allow's say that in our pretend pixel globe, all of our objects have a mass equal to i. F/ 1 = F. And so:

A = F

The acceleration of an object is equal to forcefulness. This is dandy news. After all, we saw in Affiliate 1 that dispatch was the key to controlling the motility of our objects on screen. Location is adjusted past velocity, and velocity by acceleration. Acceleration was where it all began. Now we learn that forcefulness is truly where it all begins.

Allow'due south take our Mover class, with location, velocity, and dispatch.

Now our goal is to be able to add forces to this object, perhaps saying:

or:

where wind and gravity are PVectors. According to Newton's 2nd law, we could implement this function as follows.

2.3 Force Accumulation

This looks pretty good. Later all, acceleration = strength is a literal translation of Newton'southward second constabulary (without mass). However, there's a pretty large trouble here. Let'south render to what we are trying to accomplish: creating a moving object on the screen that responds to wind and gravity.

Ok, let's be the computer for a moment. First, we telephone call applyForce() with air current. And so the Mover object'southward acceleration is now assigned the PVector air current. Second, nosotros telephone call applyForce() with gravity. Now the Mover object's dispatch is set to the gravity PVector. Third, nosotros call update(). What happens in update()? Dispatch is added to velocity.

We're not going to come across any fault in Processing, just zoinks! Nosotros've got a major problem. What is the value of acceleration when it is added to velocity? It is equal to the gravity force. Wind has been left out! If we telephone call applyForce() more than than once, it overrides each previous call. How are we going to handle more ane forcefulness?

The truth of the affair here is that we started with a simplified statement of Newton's 2d police force. Here's a more accurate way to put it:

Net Force equals mass times acceleration.

Or, acceleration is equal to the sum of all forces divided by mass. This makes perfect sense. Subsequently all, as nosotros saw in Newton's start police force, if all the forces add up to nil, an object experiences an equilibrium country (i.e. no acceleration). Our implementation of this is through a procedure known as strength aggregating . It's actually very simple; all we need to practise is add all of the forces together. At any given moment, there might exist 1, 2, vi, 12, or 303 forces. As long equally our object knows how to accumulate them, information technology doesn't matter how many forces act on information technology.

At present, nosotros're not finished but yet. Force aggregating has ane more piece. Since we're adding all the forces together at whatsoever given moment, we take to make sure that we clear acceleration (i.due east. set information technology to zero) earlier each fourth dimension update() is chosen. Let's think about air current for a moment. Sometimes the current of air is very strong, sometimes information technology'south weak, and sometimes there'due south no current of air at all. At whatsoever given moment, at that place might exist a huge gust of air current, say, when the user holds down the mouse.

When the user releases the mouse, the wind volition stop, and according to Newton'south first police force, the object volition continue to motion at a constant velocity. However, if we had forgotten to reset acceleration to zero, the gust of wind would still be in effect. Even worse, information technology would add onto itself from the previous frame, since we are accumulating forces! Acceleration, in our simulation, has no retentivity; it is simply calculated based on the ecology forces present at a moment in time. This is different than, say, location, which must call up where the object was in the previous frame in guild to motion properly to the adjacent.

The easiest way to implement clearing the acceleration for each frame is to multiply the PVector by 0 at the end of update().

Exercise 2.1

Using forces, simulate a helium-filled balloon floating upwards and bouncing off the top of a window. Tin yous add a wind force that changes over time, mayhap according to Perlin dissonance?

2.4 Dealing with Mass

OK. We've got ane tiny little addition to brand before nosotros are done with integrating forces into our Mover class and are ready to look at examples. Afterwards all, Newton's second police is really F = M × A , not A = F . Incorporating mass is every bit easy every bit adding an instance variable to our class, but we need to spend a niggling more time here because a slight complexity volition emerge.

First we just need to add mass.

Units of Measurement

At present that nosotros are introducing mass, it's important to make a quick note about units of measurement. In the real world, things are measured in specific units. Nosotros say that two objects are three meters apart, the baseball is moving at a rate of 90 miles per hour, or this bowling ball has a mass of vi kilograms. As we'll run across subsequently in this book, sometimes we will want to have real-world units into consideration. Notwithstanding, in this chapter, we're going to ignore them for the almost part. Our units of measurement are in pixels ("These two circles are 100 pixels apart") and frames of animation ("This circle is moving at a rate of 2 pixels per frame"). In the instance of mass, there isn't any unit of measurement for united states to use. We're just going to make something up. In this example, we're arbitrarily picking the number 10. At that place is no unit of measurement, though y'all might enjoy inventing a unit of your own, like "1 moog" or "1 yurkle." It should besides exist noted that, for demonstration purposes, we'll tie mass to pixels (drawing, say, a circle with a radius of 10). This will let u.s.a. to visualize the mass of an object. In the real earth, all the same, size does not definitely indicate mass. A small metal ball could have a much college mass than a big balloon due to its higher density.

Mass is a scalar (bladder), not a vector, equally it's just one number describing the amount of thing in an object. We could be fancy about things and compute the area of a shape as its mass, but it's simpler to brainstorm by maxim, "Hey, the mass of this object is…um, I dunno…how virtually x?"

This isn't so corking since things simply become interesting in one case nosotros have objects with varying mass, but information technology'll get united states started. Where does mass come in? Nosotros employ it while applying Newton's 2d law to our object.

Yet again, even though our code looks quite reasonable, we have a fairly major problem hither. Consider the post-obit scenario with two Mover objects, both existence blown away by a current of air force.

Again, allow's be the computer. Object m1 receives the wind force—(ane,0)—divides it by mass (10), and adds it to acceleration.

m1 equals wind force:     (one,0)
Divided past mass of 10:    (0.1,0)

OK. Moving on to object m2. It also receives the current of air force—(1,0). Wait. Concur on a 2d. What is the value of the wind strength? Taking a closer look, the air current forcefulness is actually now—(0.1,0)!! Do you lot remember this little tidbit about working with objects? When you pass an object (in this instance a PVector) into a office, you are passing a reference to that object. It's not a copy! So if a office makes a change to that object (which, in this example, information technology does by dividing past mass) and so that object is permanently changed! Simply nosotros don't desire m2 to receive a force divided past the mass of object m1. We want information technology to receive that forcefulness in its original state—(i,0). And and so we must protect ourselves and make a copy of the PVector f before dividing it by mass. Fortunately, the PVector class has a convenient method for making a re-create—become(). become() returns a new PVector object with the same data. And so we can revise applyForce() as follows:

There's another style we could write the in a higher place function, using the static method div(). For help with this exercise, review static methods in Chapter 1.

Exercise ii.2

Rewrite the applyForce() method using the static method div() instead of get().

2.5 Creating Forces

Permit's accept a moment to remind ourselves where nosotros are. We know what a forcefulness is (a vector), and we know how to utilize a force to an object (dissever it past mass and add it to the object's acceleration vector). What are we missing? Well, nosotros have yet to effigy out how we go a force in the get-go identify. Where practice forces come up from?

In this chapter, we'll look at two methods for creating forces in our Processing world.

  1. Brand up a force! Later all, yous are the programmer, the creator of your world. There's no reason why you can't only brand up a forcefulness and apply it.

  2. Model a strength! Aye, forces exist in the real world. And physics textbooks often contain formulas for these forces. We tin can take these formulas, interpret them into source code, and model real-world forces in Processing.

The easiest mode to make upwards a force is to just option a number. Permit's offset with the idea of simulating wind. How well-nigh a wind strength that points to the right and is fairly weak? Assuming a Mover object yard, our code would look like:

The event isn't terribly interesting, but it is a good identify to showtime. We create a PVector object, initialize it, and pass it into an object (which in turn will apply it to its own acceleration). If we wanted to take two forces, perhaps air current and gravity (a chip stronger, pointing down), we might write the following:

Your browser does not support the sail tag.

Example 2.1: Forces

At present nosotros have two forces, pointing in dissimilar directions with different magnitudes, both applied to object thou. Nosotros're commencement to go somewhere. We've now built a world for our objects in Processing, an environment to which they can actually reply.

Let's await at how we could make this example a bit more exciting with many objects of varying mass. To do this, we'll demand a quick review of object-oriented programming. Again, we're not roofing all the basics of programming here (for that yous can bank check out whatsoever of the intro Processing books listed in the introduction). However, since the idea of creating a earth filled with objects is pretty fundamental to all the examples in this book, it's worth taking a moment to walk through the steps of going from i object to many.

This is where we are with the Mover class every bit a whole. Notice how it is identical to the Mover class created in Affiliate 1, with 2 additions—mass and a new applyForce() part.

Now that our class is set, we can choose to create, say, 1 hundred Mover objects with an array.

And then we can initialize all of those Mover objects in setup() with a loop.

Merely at present nosotros have a small issue. If we refer back to the Mover object's constructor…

…we discover that every Mover object is fabricated exactly the same manner. What we want are Mover objects of varying mass that start at varying locations. Here is where nosotros need to increase the sophistication of our constructor past calculation arguments.

Notice how the mass and location are no longer set to hardcoded numbers, but rather initialized via arguments passed through the constructor. This means we can create a multifariousness of Mover objects: big ones, small ones, ones that start on the left side of the screen, ones that starting time on the correct, etc.

With an assortment, however, we want to initialize all of the objects with a loop.

For each mover created, the mass is set to a random value between 0.i and 5, the starting ten-location is fix to 0, and the starting y-location is set to 0. Certainly, there are all sorts of ways nosotros might choose to initialize the objects; this is simply a demonstration of i possibility.

Once the array of objects is declared, created, and initialized, the rest of the code is simple. We run through every object, hand them each the forces in the surround, and enjoy the show.

Your browser does not support the canvas tag.

Example ii.ii: Forces acting on many objects

Notation how in the in a higher place image, the smaller circles reach the right of the window faster than the larger ones. This is because of our formula: acceleration = force divided past mass. The larger the mass, the smaller the acceleration.

Exercise 2.iii

Instead of objects bouncing off the border of the wall, create an example in which an invisible force pushes dorsum on the objects to continue them in the window. Can y'all weight the force according to how far the object is from an edge—i.eastward., the closer it is, the stronger the forcefulness?

ii.half dozen Gravity on Globe and Modeling a Force

You may take noticed something woefully inaccurate about this last example. The smaller the circle, the faster it falls. There is a logic to this; after all, we just stated (according to Newton's second law) that the smaller the mass, the higher the acceleration. But this is non what happens in the real world. If you were to climb to the superlative of the Leaning Tower of Pisa and drib two balls of different masses, which one will striking the ground get-go? According to legend, Galileo performed this verbal exam in 1589, discovering that they fell with the same acceleration, hit the basis at the same time. Why is this? Every bit nosotros will see later in this affiliate, the force of gravity is calculated relative to an object's mass. The bigger the object, the stronger the force. So if the force is scaled co-ordinate to mass, it is canceled out when acceleration is divided by mass. Nosotros tin implement this in our sketch rather easily past multiplying our made-up gravity strength by mass.

Your browser does not support the canvas tag.

Instance 2.3: Gravity scaled by mass

While the objects now autumn at the aforementioned rate, considering the strength of the wind force is independent of mass, the smaller objects all the same accelerate to the right more quickly.

Making up forces volition actually get u.s.a. quite far. The world of Processing is a pretend world of pixels and you are its primary. And so whatever you deem advisable to be a force, well by golly, that's the force it should exist. Nonetheless, at that place may come a time where y'all find yourself wondering: "Merely how does information technology really all work?"

Open up any high school physics textbook and you volition find some diagrams and formulas describing many different forces—gravity, electromagnetism, friction, tension, elasticity, and more. In this chapter we're going to look at two forces—friction and gravity. The indicate we're making here is not that friction and gravity are central forces that y'all e'er need to accept in your Processing sketches. Rather, we want to evaluate these two forces as case studies for the post-obit process:

  • Understanding the concept behind a force

  • Deconstructing the forcefulness's formula into two parts:

    • How exercise nosotros compute the force'south direction?

    • How do we compute the force's magnitude?

  • Translating that formula into Processing code that calculates a PVector to be sent through our Mover's applyForce() function

If we tin can follow the higher up steps with two forces, then hopefully if you ever discover yourself Googling "atomic nuclei weak nuclear force" at 3 a.thou., you will have the skills to accept what y'all find and adapt it for Processing.

Dealing with formulae

OK, in a moment we're going to write out the formula for friction. This isn't the outset time nosotros've seen a formula in this book; nosotros just finished up our word of Newton'southward second law, F = M × A (or force = mass * acceleration). We didn't spend a lot of time worrying virtually this formula because information technology's a prissy and uncomplicated 1. However, it's a scary world out there. Just accept a wait at the equation for a "normal" distribution, which we covered (without looking at the formula) in the Introduction.

f x ; µ , σ 2 = 1 σ 2 π e - x - µ 2 2 σ 2

What we're seeing here is that formulas like to use a lot of symbols (quite oftentimes letters from the Greek alphabet). Let's accept a expect at the formula for friction.

F r i c t i o n = - µ N v

If it'southward been a while since you've looked at a formula from a math or physics textbook, there are three key points that are of import to cover before we move on.

  • Evaluate the correct side, assign to the left side. This is just similar in code! What we're doing here is evaluating the right side of the equation and assigning it to the left. In the instance above, we want to calculate the forcefulness of friction—the left side tells us what nosotros desire to calculate and the right side tells us how to do it.

  • Are we talking well-nigh a vector or a scalar? Information technology's important for us to realize that in some cases, we'll be looking at a vector; in others, a scalar. For case, in this instance the force of friction is a vector. Nosotros can see that by the arrow above the word "friction." Information technology has a magnitude and management. The right side of the equation besides has a vector, equally indicated by the symbol 5 , which in this case stands for the velocity unit vector.

  • When symbols are placed side by side to each other, we mean for them to be multiplied. The formula above actually has four elements: -1, μ, Due north, and five . We want to multiply them together and read the formula as:

    F r i c t i o north = - 1 * µ * N * 5

2.vii Friction

Let'southward begin with friction and follow our steps.

Friction is a dissipative strength . A dissipative force is one in which the total free energy of a organization decreases when an object is in movement. Let's say yous are driving a car. When you press your human foot down on the brake pedal, the motorcar's brakes use friction to slow down the motion of the tires. Kinetic energy (motion) is converted into thermal energy (heat). Whenever two surfaces come up into contact, they feel friction. A complete model of friction would include separate cases for static friction (a body at rest against a surface) and kinetic friction (a body in move against a surface), but for our purposes, we are only going to look at the kinetic case.

Here's the formula for friction:

Nature of Code Image

Effigy 2.three

It's now up to us to separate this formula into two components that decide the direction of friction as well as the magnitude. Based on the diagram to a higher place, we can see that friction points in the opposite direction of velocity. In fact, that'south the part of the formula that says -i * v , or -1 times the velocity unit vector. In Processing, this would mean taking the velocity vector, normalizing it, and multiplying by -ane.

Notice ii additional steps here. Showtime, it's important to make a re-create of the velocity vector, every bit we don't want to reverse the object'southward direction by accident. Second, we normalize the vector. This is because the magnitude of friction is non associated with how fast it is moving, and we want to get-go with a friction vector of magnitude 1 then that it can easily exist scaled.

According to the formula, the magnitude is μ * N. μ, the Greek letter mu (pronounced "mew"), is used here to depict the coefficient of friction . The coefficient of friction establishes the strength of a friction forcefulness for a particular surface. The higher it is, the stronger the friction; the lower, the weaker. A block of water ice, for example, will have a much lower coefficient of friction than, say, sandpaper. Since we're in a pretend Processing world, we tin can arbitrarily set the coefficient based on how much friction we want to simulate.

At present for the 2d function: N. N refers to the normal force , the force perpendicular to the object's motility along a surface. Think of a vehicle driving forth a route. The vehicle pushes down against the road with gravity, and Newton's third law tells united states of america that the road in turn pushes back against the vehicle. That's the normal strength. The greater the gravitational forcefulness, the greater the normal force. Every bit nosotros'll see in the side by side section, gravity is associated with mass, and so a lightweight sports machine would experience less friction than a massive tractor trailer truck. With the diagram higher up, however, where the object is moving along a surface at an bending, computing the normal force is a flake more than complicated because it doesn't indicate in the same direction every bit gravity. Nosotros'll need to know something almost angles and trigonometry.

All of these specifics are important; yet, in Processing, a "skilful enough" simulation can be achieved without them. We tin, for example, make friction work with the assumption that the normal force will ever have a magnitude of 1. When we get into trigonometry in the next chapter, we'll remember to return to this question and make our friction example a bit more sophisticated. Therefore:

At present that we take both the magnitude and direction for friction, nosotros can put information technology all together…

…and add it to our "forces" case, where many objects experience air current, gravity, and now friction:

Your browser does not support the sail tag.

No friction

Your browser does non support the canvas tag.

With friction

Example 2.iv: Including friction

Running this example, you lot'll find that the circles don't even arrive to the right side of the window. Since friction continuously pushes confronting the object in the contrary management of its motility, the object continuously slows down. This tin can be a useful technique or a trouble depending on the goals of your visualization.

Exercise ii.iv

Create pockets of friction in a Processing sketch so that objects only experience friction when crossing over those pockets. What if you vary the strength (friction coefficient) of each area? What if you make some pockets feature the opposite of friction—i.e., when you enter a given pocket you actually speed up instead of slowing down?

2.eight Air and Fluid Resistance

Nature of Code Image

Effigy 2.4

Friction as well occurs when a trunk passes through a liquid or gas. This strength has many different names, all actually meaning the same thing: gluey force, elevate force, fluid resistance. While the result is ultimately the same as our previous friction examples (the object slows down), the way in which we calculate a drag force will be slightly different. Let'south look at the formula:

F d = - 1 2 ρ v two A C d v

At present let'south pause this down and see what we actually need for an constructive simulation in Processing, making ourselves a much simpler formula in the procedure.

  • F d refers to drag force, the vector we ultimately want to compute and pass into our applyForce() part.

  • - 1/2 is a constant: -0.v. This is fairly irrelevant in terms of our Processing world, as we will exist making up values for other constants anyway. Nevertheless, the fact that it is negative is important, as it tells us that the forcefulness is in the opposite direction of velocity (merely as with friction).

  • ρ is the Greek letter of the alphabet rho, and refers to the density of the liquid, something nosotros don't need to worry near. We can simplify the problem and consider this to take a abiding value of 1.

  • v refers to the speed of the object moving. OK, nosotros've got this ane! The object'southward speed is the magnitude of the velocity vector: velocity.magnitude(). And v two just means five squared or v * v .

  • A refers to the frontal area of the object that is pushing through the liquid (or gas). An aerodynamic Lamborghini, for instance, will experience less air resistance than a boxy Volvo. Nevertheless, for a bones simulation, we tin consider our object to be spherical and ignore this element.

  • C d is the coefficient of elevate, exactly the same as the coefficient of friction ( ρ ). This is a constant we'll determine based on whether we want the drag forcefulness to be strong or weak.

  • v Look familiar? It should. This refers to the velocity unit vector, i.east. velocity.normalize(). Just like with friction, elevate is a force that points in the opposite management of velocity.

Now that we've analyzed each of these components and adamant what we need for a simple simulation, we can reduce our formula to:

Nature of Code Image

Effigy 2.5: Our simplified elevate force formula

or:

Let'south implement this force in our Mover form example with one addition. When nosotros wrote our friction case, the forcefulness of friction was e'er present. Whenever an object was moving, friction would slow it down. Here, allow'south introduce an element to the environment—a "liquid" that the Mover objects pass through. The Liquid object volition be a rectangle and volition know about its location, width, meridian, and "coefficient of drag"—i.due east., is it easy for objects to motility through it (like air) or difficult (like molasses)? In addition, it should include a function to depict itself on the screen (and two more functions, which we'll run across in a moment).

The master program will at present include a Liquid object reference every bit well as a line of code that initializes that object.

Now comes an interesting question: how do we get the Mover object to talk to the Liquid object? In other words, we want to execute the following:

When a mover passes through a liquid it experiences a drag force.

…or in object-oriented speak (assuming we are looping through an array of Mover objects with alphabetize i):

The above code tells us that we demand to add together two functions to the Mover course: (i) a function that determines if a Mover object is inside the Liquid object, and (2) a function that computes and applies a drag strength on the Mover object.

The offset is piece of cake; nosotros can merely use a conditional statement to decide if the location vector rests within the rectangle defined by the liquid.

The drag() office is a bit more complicated; however, we've written the code for it already. This is simply an implementation of our formula. The drag force is equal to the coefficient of drag multiplied by the speed of the Mover squared in the contrary direction of velocity!

And with these two functions added to the Mover course, we're ready to put it all together in the principal tab:

Your browser does not support the canvas tag.

Example 2.5: Fluid Resistance

Running the example, you should notice that we are simulating balls falling into water. The objects only deadening down when crossing through the gray area at the bottom of the window (representing the liquid). Yous'll also detect that the smaller objects slow down a great deal more than the larger objects. Retrieve Newton's 2nd police? A = F / Thou. Acceleration equals force divided past mass. A massive object will accelerate less. A smaller object volition accelerate more. In this case, the dispatch nosotros're talking about is the "slowing down" due to drag. The smaller objects will slow downward at a greater rate than the larger ones.

Do 2.v

Accept a look at our formula for drag again: drag force = coefficient * speed * speed . The faster an object moves, the greater the elevate force against information technology. In fact, an object not moving in water experiences no drag at all. Expand the example to drop the balls from different heights. How does this affect the drag as they hit the water?

Practice 2.half dozen

The formula for drag besides included surface area. Can you create a simulation of boxes falling into water with a drag force dependent on the length of the side hitting the water?

Practise two.7

Fluid resistance does not only work opposite to the velocity vector, but also perpendicular to it. This is known as "lift-induced drag" and volition cause an airplane with an angled wing to ascent in altitude. Endeavor creating a simulation of lift.

2.9 Gravitational Attraction

Nature of Code Image

Figure 2.half-dozen

Probably the virtually famous force of all is gravity. We humans on earth recollect of gravity as an apple tree striking Isaac Newton on the head. Gravity means that stuff falls downward. But this is but our experience of gravity. In truth, simply every bit the earth pulls the apple towards it due to a gravitational force, the apple pulls the earth too. The thing is, the earth is just then freaking big that it overwhelms all the other gravity interactions. Every object with mass exerts a gravitational force on every other object. And there is a formula for calculating the strengths of these forces, as depicted in Figure 2.6.

Let'due south examine this formula a bit more than closely.

  • F refers to the gravitational forcefulness, the vector we ultimately want to compute and laissez passer into our applyForce() function.

  • K is the universal gravitational abiding, which in our world equals six.67428 ten x-eleven meters cubed per kilogram per 2d squared. This is a pretty important number if your name is Isaac Newton or Albert Einstein. Information technology's non an important number if you are a Processing programmer. Again, it's a constant that we can utilize to make the forces in our globe weaker or stronger. Just making it equal to one and ignoring it isn't such a terrible selection either.

  • thousandane and mtwo are the masses of objects i and ii. As we saw with Newton's second law ( F = M × A ), mass is also something we could choose to ignore. After all, shapes drawn on the screen don't actually have a physical mass. However, if we keep these values, we can create more interesting simulations in which "bigger" objects exert a stronger gravitational force than smaller ones.

  • r refers to the unit of measurement vector pointing from object one to object two. As we'll encounter in a moment, we can compute this management vector by subtracting the location of 1 object from the other.

  • r 2 refers to the distance between the two objects squared. Allow'due south take a moment to think most this a bit more than. With everything on the top of the formula—Chiliad, g1 , chiliad2 —the bigger its value, the stronger the force. Big mass, big strength. Big G, large force. Now, when we divide by something, we accept the contrary. The strength of the strength is inversely proportional to the altitude squared. The farther away an object is, the weaker the force; the closer, the stronger.

Hopefully by now the formula makes some sense to us. We've looked at a diagram and dissected the individual components of the formula. Now it'southward fourth dimension to figure out how we interpret the math into Processing code. Let's brand the following assumptions.

Nosotros take two objects, and:

  1. Each object has a location: PVector location1 and PVector location2.

  2. Each object has a mass: float mass1 and float mass2.

  3. There is a variable float Yard for the universal gravitational constant.

Given these assumptions, nosotros want to compute PVector forcefulness, the force of gravity. Nosotros'll practise it in ii parts. First, we'll compute the direction of the strength r in the formula higher up. 2d, we'll calculate the forcefulness of the force according to the masses and distance.

Nature of Code Image

Effigy 2.7

Think in Chapter 1, when we figured out how to have an object advance towards the mouse? (Run into Figure ii.7.)

A vector is the departure between two points. To make a vector that points from the circle to the mouse, we but subtract one point from another:

In our case, the direction of the attraction forcefulness that object i exerts on object ii is equal to:

Don't forget that since nosotros desire a unit vector, a vector that tells us about direction only, we'll need to normalize the vector after subtracting the locations.

OK, nosotros've got the direction of the force. Now we just need to compute the magnitude and calibration the vector appropriately.

Nature of Code Image

Figure 2.8

The only problem is that we don't know the altitude. K, mass1, and mass2 were all givens, but we'll demand to actually compute altitude before the above code will work. Didn't we just make a vector that points all the way from i location to another? Wouldn't the length of that vector be the distance between two objects?

Well, if we add just one line of code and grab the magnitude of that vector earlier normalizing it, and then we'll have the altitude.

Notation that I likewise renamed the PVector "dir" as "strength." Afterwards all, when we're finished with the calculations, the PVector we started with ends upward being the actual force vector we wanted all forth.

Now that we've worked out the math and the code for calculating an attractive force (emulating gravity), we demand to turn our attending to applying this technique in the context of an actual Processing sketch. In Example 2.ane, you lot may recall how nosotros created a simple Mover object—a class with PVector's location, velocity, and acceleration as well every bit an applyForce(). Let's take this verbal class and put it in a sketch with:

Nature of Code Image

Figure 2.nine

  • A unmarried Mover object.

  • A single Attractor object (a new course that will have a fixed location).

The Mover object will experience a gravitational pull towards the Attractor object, as illustrated in Effigy 2.9.

We can start by making the new Attractor grade very simple—giving it a location and a mass, along with a office to brandish itself (tying mass to size).

And in our main programme, nosotros can add an instance of the Attractor class.

This is a skillful structure: a primary program with a Mover and an Attractor object, and a class to handle the variables and behaviors of movers and attractors. The last piece of the puzzle is how to become ane object to attract the other. How do we get these 2 objects to talk to each other?

There are a number of ways nosotros could do this. Here are just a few possibilities.

Task Role
1. A function that receives both an Attractor and a Mover:
attraction(a,g);
two. A office in the Attractor class that receives a Mover:
a.attract(k);
3. A function in the Mover form that receives an Attractor:
m.attractedTo(a);
4. A role in the Attractor course that receives a Mover and returns a PVector, which is the allure force. That attraction force is then passed into the Mover'southward applyForce() office:
PVector f = a.attract(grand); m.applyForce(f);                  

and so on. . .

It'southward good to look at a range of options for making objects talk to each other, and you could probably make arguments for each of the above possibilities. I'd like to at least discard the start one, since an object-oriented approach is really a much better choice over an arbitrary function not tied to either the Mover or Attractor course. Whether you pick option 2 or pick 3 is the difference between maxim "The attractor attracts the mover" or "The mover is attracted to the attractor." Number four is really my favorite, at least in terms of where nosotros are in this book. Afterward all, we spent a lot of fourth dimension working out the applyForce() function, and I call back our examples will exist clearer if we continue with the same methodology.

In other words, where we once had:

We now accept:

And then our draw() function can at present be written as:

We're virtually at that place. Since we decided to put the attract() function inside of the Attractor class, we'll need to actually write that part. The function needs to receive a Mover object and return a PVector, i.e.:

And what goes inside that office? All of that nice math we worked out for gravitational attraction!

And we're washed. Sort of. Well-nigh. At that place'south one small kink we need to work out. Let's look at the above lawmaking again. Come across that symbol for divide, the slash? Whenever nosotros have ane of these, we need to enquire ourselves the question: What would happen if the altitude happened to be a really, actually small number or (even worse!) zero??! Well, we know we tin can't divide a number by 0, and if we were to divide a number past something like 0.0001, that is the equivalent of multiplying that number by 10,000! Aye, this is the real-world formula for the strength of gravity, but nosotros don't live in the real world. We live in the Processing world. And in the Processing globe, the mover could end upwardly being very, very close to the attractor and the strength could become so strong the mover would just fly way off the screen. And then with this formula, it'south practiced for us to exist practical and constrain the range of what altitude tin can actually exist. Peradventure, no thing where the Mover really is, we should never consider it less than 5 pixels or more than 25 pixels away from the attractor.

For the same reason that nosotros need to constrain the minimum distance, it's useful for u.s.a. to do the aforementioned with the maximum. After all, if the mover were to be, say, 500 pixels from the attractor (not unreasonable), nosotros'd be dividing the force by 250,000. That strength might end up being so weak that it's almost equally if we're not applying information technology at all.

Now, it's really up to you to make up one's mind what behaviors you desire. But in the case of, "I want reasonable-looking attraction that is never absurdly weak or strong," then constraining the distance is a skillful technique.

Our Mover class hasn't inverse at all, so let'southward but look at the chief programme and the Attractor form as a whole, adding a variable M for the universal gravitational abiding. (On the website, you'll discover that this example also has code that allows y'all to move the Attractor object with the mouse.)

Your browser does not support the canvas tag.

Example 2.6: Attraction

And we could, of course, expand this instance using an array to include many Mover objects, just as we did with friction and elevate:

Your browser does non support the canvass tag.

Example two.vii: Attraction with many Movers

Exercise 2.8

In the instance above, nosotros have a arrangement (i.due east. assortment) of Mover objects and i Attractor object. Build an instance that has systems of both movers and attractors. What if you make the attractors invisible? Can you create a blueprint/design from the trails of objects moving effectually attractors? See the Metropop Denim project by Clayton Cubitt and Tom Carden for an example.

Practice ii.9

It'south worth noting that gravitational attraction is a model we can follow to develop our own forces. This chapter isn't suggesting that you should exclusively create sketches that employ gravitational allure. Rather, you should be thinking creatively nearly how to design your own rules to drive the behavior of objects. For case, what happens if you lot design a force that is weaker the closer it gets and stronger the farther information technology gets? Or what if you design your attractor to attract faraway objects, merely repel shut ones?

2.10 Everything Attracts (or Repels) Everything

Hopefully, yous found it helpful that we started with a simple scenario—1 object attracts another object—and moved on to one object attracts many objects. However, it's probable that you are going to discover yourself in a slightly more than complex situation: many objects attract each other. In other words, every object in a given organization attracts every other object in that system (except for itself).

We've really done almost all of the work for this already. Let'southward consider a Processing sketch with an array of Mover objects:

The draw() function is where nosotros need to work some magic. Currently, we're saying: "for every mover i, update and display yourself." Now what we need to say is: "for every mover i, be attracted to every other mover j, and update and display yourself."

To do this, nosotros need to nest a 2nd loop.

In the previous case, we had an Attractor object with a function named attract(). Now, since nosotros accept movers attracting movers, all we need to do is copy the attract() function into the Mover class.

Of course, at that place'southward one small-scale trouble. When we are looking at every mover i and every mover j, are we OK with the times that i equals j? For instance, should mover #3 attract mover #3? The respond, of course, is no. If in that location are 5 objects, nosotros only want mover #3 to attract 0, 1, 2, and four, skipping itself. And so, we end this example past adding a simple conditional statement to skip applying the force when i equals j.

Your browser does not back up the sheet tag.

Example 2.eight: Mutual attraction

Practise ii.10

Change the attraction force in Example 2.8 to a repulsion force. Can you create an instance in which all of the Mover objects are attracted to the mouse, but repel each other? Call up about how you lot demand to rest the relative force of the forces and how to most finer use altitude in your force calculations.

The Ecosystem Project

Step ii Practice:

Incorporate the concept of forces into your ecosystem. Try introducing other elements into the environment (food, a predator) for the creature to interact with. Does the creature experience allure or repulsion to things in its world? Tin can you recall more abstractly and design forces based on the creature's desires or goals?

bondmork1952.blogspot.com

Source: https://natureofcode.com/book/chapter-2-forces/

0 Response to "How Do You Know Mass and Acceleration Are Inversely Proportional"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel