So far, we’ve modeled everything in this series as particles. Particles are the simplest way to model something physically, because they only have a location in space and don't have a size or shape. Particles can only translate (move), and can’t rotate.

]]>This article is part of the

So far, we’ve modeled everything in this series as particles. Particles are the simplest way to model something physically, because they only have a location in space and don't have a size or shape. Particles can only translate (move), and can’t rotate.

This article is part of the Physics in Javascript series. If you feel lost reading this article, you may want to read the Gravity and Drag and Spring-Mass-Damper articles.

Just looking for the cool JSFiddle code example?

And while you can do some amazing things just by modeling particles, particles aren't realistic in the real world. Real objects aren't just infinitely small dots. Real objects have a size and shape and most importantly, an orientation. Real objects can rotate. And since most of you are probably interested in game development: you can't get by on particles alone.

Today we're going to begin our discussion of rigid bodies. Rigid bodies have all of the properties of particles: they have a location, they have a linear velocity, and they have a linear acceleration. But because rigid bodies have a shape and size, they also have an orientation (a rotation angle), and are subject not just to forces but also to torques which cause them to rotate. Torques can either be applied to an object directly (in the case of a wheel on a motor, like in a car), or they can appear because a force is applied to an object off-center (like when a football is kicked and tumbles end-over-end).

While rigid bodies are more complicated to model than particles, we’re still able to use familiar concepts and Newton’s laws. We just need to extend them a little bit to deal with rotation and torque.

Concretely: the angle θ is the number of radians or degrees something is rotated by.

Similarly, angular acceleration is given in “radians per second squared” or “radians per second, per second”, and is typically denoted by the Greek letter alpha: α.

What’s more, a torque is just a force applied in a special manner: torque is what you get when you apply a force slightly offset from an object’s center of mass. If you were to lay a block on a table and push on it dead-center with your finger, you’d push the block forward without rotating it. If, however, your finger were off to the side of the block, you’d end up both pushing and rotating the block. It’s still the same block, it’s still the same finger. The only thing that has changed is where you applied the force. Since you applied it in such a way that it didn’t go “through” the block’s center of mass, you created a torque and that’s what caused the block to rotate.

A torque, therefore, is just a force multiplied by its (perpendicular) distance from the object’s center of mass (or point of rotation, depending on your physical set-up). Think about using a wrench: the longer the wrench is, the easier it is to turn. That’s because you’re multiplying the force by a larger distance and getting a larger torque as a result (of course, you have to move your hand farther to get the same angle of motion with a longer wrench -- so you end up doing the same amount of work!).

Torque is measured in units of force times distance: newton-meters or pound-feet, and is typically denoted by the Greek letter tau: τ.

The moment of inertia is given in units of kg * m^{2} (kilogram times meters squared) and is typically denoted by the capital letter I or J. I like J.

Fortunately, you can just look up the moments of inertia of many common shapes and use those in your calculations. In school we were forced to do those calculations by hand with double or triple integrals. If you’re interested in practicing your calculus, go that route. If not, just use the lookup table.

Since you’ve certainly read the Gravity and Drag and Spring-Mass-Damper articles, you probably already know what to do with this equation. Figure out the total torque, use that to calculate the acceleration, and then integrate twice to get the angle. The trickiest part is the "figure out the net torque" step, especially if you're uncomfortable with trigonometry. Let’s dive into an example.

I should now point out that -- just like with linear motion -- you can introduce springs and dampers into the mix. The equations are essentially the same as their linear counterparts. If you want a homework assignment, please try adding a damper to this pendulum!

The pendulum itself will be modeled as a point mass at the end of a weightless rod. Many physics problems are made with such assumptions: point mass, weightless rod, no friction, etc. It's a good way to make a first pass at what could become a very complicated problem.

Diving right into some code:

```
var pendulum = {mass: 1, length:500, theta: (Math.PI/2) - 0.05, omega: 0, alpha:0, J:0};
var setup = function() {
pendulum.J = pendulum.mass * pendulum.length * pendulum.length;
...
}
```

Right off the bat we set up initial conditions for our pendulum. In this case, we've defined θ = 0 to be when the pendulum is pointing horizontally to the right. Many people would choose to define θ = 0 as downwards. It doesn't really matter, as long as you're consistent.

Then we calculate the value of the pendulum's moment of inertia. Our Wikipedia list of moments of inertia tells us that a "point mass m at distance r from the axis of rotation" has a moment of inertia of m*r^{2}, so that's what we use.

`requestAnimFrame()`

instead of `setInterval()`

(see the JSFiddle for the full code; I won't talk about it here). Secondly, instead of using Euler's method of numerical integration, I've used the velocity verlet method.
Euler's method is actually pretty inaccurate as far as numerical integration methods go. I've used it up until now because it's very simple to understand, but it's time to move onwards and upwards. You're ready for it!

The above graphic illustrates where the inaccuracy in Euler's method comes from. Numerical integration is all about calculating the area below a function's curve. Most basic numerical integration techniques draw rectangles underneath the curve and add up their areas (see Riemann sum); this is what we're doing with Euler's method. Unfortunately, this can grossly over- or under-estimate a function especially if that function changes quickly. Making those rectangles thinner (in our case, making the loop delay smaller/faster) can help greatly, but there's still the fact that we're putting the the corner of the rectangle on the curve.

One other integration technique improves accuracy by having the function run through the midpoint of the rectangle, instead of the left or right corner; this is called the midpoint method. There's also the trapezoidal method, which draws trapezoids instead of rectangles. There's also the very accurate Runge-Kutta method, which uses a weighted average of 4 points along the function to calculate the area below the curve.

Here's a nice demonstration of how much better the midpoint method (in green) works compared to Euler's method (blue).

To make a long story short, we'll use the velocity verlet method today. I encourage you to look up the details and try to understand what gives it an advantage over Euler's method!

```
var loop = function() {
...
/* Velocity Verlet */
/* Calculate current position from last frame's position, velocity, and acceleration */
pendulum.theta += pendulum.omega * deltaT + ( 0.5 * pendulum.alpha * deltaT * deltaT );
/* Calculate forces from current position. */
var T = pendulum.mass * 9.81 * Math.cos(pendulum.theta) * pendulum.length;
/* Current acceleration */
var alpha = T / pendulum.J;
/* Calculate current velocity from last frame's velocity and
average of last frame's acceleration with this frame's acceleration. */
pendulum.omega += 0.5 * (alpha + pendulum.alpha) * deltaT;
/* Update acceleration */
pendulum.alpha = alpha;
var px = width/2 + pendulum.length*Math.cos(pendulum.theta);
var py = 50 + pendulum.length*Math.sin(pendulum.theta);
...
};
```

The velocity verlet method has us do things "out of order", so to speak. I'll describe the steps in the order I feel is natural, however, starting with torque:

First we calculate the torque on the pendulum. Since gravity pulls downwards at all times, we need to use some trigonometry to get the component of the pendulum's weight that's pulling the pendulum towards the center -- the small portion of the weight pointed perpendicular to the pendulum itself. Because of the fact that we set up the θ = 0 point on the right horizontal, we get this by calculating m * g * cos(θ) -- (where m is the pendulum's mass and g is 9.81 m/s^{2}, the acceleration due to gravity on Earth).

Since we're looking for a torque, we have to multiply that perpendicular force by its distance from the center.

Once we have the torque the next few steps are easy. We calculate the angular acceleration α, and then we implement a piece of velocity verlet to get the angular velocity ω: we use the average of last frame's and this frame's acceleration in the calculation.

Finally, we calculate the angle θ. Notice this time I kept the 0.5 * α * Δt^{2} in the equation. Up until now I've left that term out -- Δt is pretty small, and squaring it makes it so small it's almost negligible. But let's leave it in here now just as a demonstration!

And that's it for the physics. The next part is a little trigonometry: we have to convert our radius and angle to x- and y-coordinates for the canvas. This is achieved readily with sine and cosine.

As an added bonus, we draw a cute little clock. See the JSFiddle for details.

If you like these articles please tell your friends, please sign up for the mailing list below, and consider following me on Twitter. Readers like you following the blog and subscribing to the mailing list gives me the motivation to write these articles -- and potentially an e-book in the future!

You may also like my Machine Learning in Javascript series.

Our big project -- our goal -- for this mechanics/dynamics portion of Modeling Physics in Javascript is to model a car's suspension system. It'll take us three non-consecutive articles to get there, but it's a worthy system to model. If you can model a car suspension then it's safe

]]>Our big project -- our goal -- for this mechanics/dynamics portion of Modeling Physics in Javascript is to model a car's suspension system. It'll take us three non-consecutive articles to get there, but it's a worthy system to model. If you can model a car suspension then it's safe to say you know how to model dynamics systems.

Today, we'll be talking about arguably the most important set of building blocks there is: the spring-mass-damper.

The spring-mass-damper is important to learn because it's everywhere in mechanics. Superficially, the system is just a block connected to a wall by a spring and a damper (we'll talk about what a damper is in a bit). But as you can imagine, physics is a can of worms -- and there's a lot more to this simple system than meets the eye.

The reason springs are so important is because there's nothing in the real universe that's "infinitely rigid". Every object in the universe is a little bit springy, even if you can't tell by eye.

Imagine you're holding a stick from one end and you rest the other end against a cup on a table. You want to push the cup across the table, so you start pushing the stick with your hand. As it turns out, the cup does *not *start moving the instant you start moving your hand. There's a tiny delay -- a fraction of a second -- before the cup starts moving.

That's because the stick isn't "infinitely rigid" -- the molecules in the stick don't all move at once. The stick is actually a spring! If you now re-imagine that scenario with a big, floppy spring, you can immediately see why the cup doesn't start moving instantly: the spring has to compress a little bit first, and only when it compresses enough does the cup start moving. Additionally, the force from your end of the spring takes some time to travel down to the other end of the spring -- think about wiggling a slinky back and forth. You're not moving the whole object instantaneously, but rather you're sending a little shockwave through the spring.

(By the way, the speed of that shockwave is called the "speed of sound", and every different material has a different speed of sound.)

Back to the stick: it's really a spring; a very, very stiff spring (the term "stiffness" actually refers to something slightly different, but for this article I'll use "stiffness" and "spring constant" interchangeably). A big floppy spring isn't very stiff, and so you can compress it quite a bit before it builds up enough force to move the cup. But imagine a stiffer spring: it needs less compression before the cup moves. Even a metal rod is a spring. You can't see it with your eyes or feel it with your hand, but the metal rod *does *compress a little bit before the other end moves. It's just so stiff that you can't see the compression with the naked eye.

So not only can actual springs be modeled as springs (mathematically) but so can sticks and rods! They're just really stiff springs. And you can even connect individual particles to each other by springs to make a realistic fluid or fabric particle simulator. So as I said: springs are everywhere.

Fortunately for us, the basic method of modeling springs is really easy. It's governed by Hooke's Law, which says this:

**F _{spring}** = -k

The force that a spring pushes or pulls with is -k (called the "spring constant", measured in kg / s^{2}) times the displacement. Let's look a little closer:

The displacement is how much the spring is being stretched or compressed. If a spring wants to be 10 inches long (we'll call this "equilibrium length" or "natural length"), but it's being crushed to 8 inches, the displacement is 2 inches.

The spring constant is a characteristic of the spring itself. We'll assume that it's a constant, but that's not true in the real world. The value of "k" changes due to things like temperature and if the spring is stretched to an extreme, but the assumption that "k" is a constant is usually a good one. There are also springs designed to have a non-constant "k", but we'll avoid those too.

The spring constant is also negative; that implies that the spring force *fights* the direction you're displacing the spring. If you stretch a spring, it tries to compress itself. If you compress a spring, it tries to stretch itself. The spring wants to be back to its equilibrium length, and the farther it is from its natural length, the harder it'll push back.

In short: a spring *resists changes in displacement.*

Why are dampers so important? Just like springs, *actual* dampers are not used everywhere (in cars we call them "shock absorbers"), but the mathematic model *is* seen everywhere. Dampers often represent the internal frictional losses of a system.

Mathematically, if you had just a perfect mass and a perfect spring and "plucked" it in a vacuum, the mass would oscillate back and forth *forever*, always returning to the same exact two extreme points. But intuition and a lifetime of experience tells us that shouldn't happen, even in a vacuum! The spring itself is made of metal, and when the spring flexes the molecules rub up against each other -- that causes friction, and friction takes away from the energy of the sprung mass. The result is that (even in a vacuum) the spring will warm up slightly and the mass will eventually stop moving.

But it's really difficult to model the internal material friction of the metal in the spring. So instead, we assume the spring is perfect ("ideal"), and add a damper to the system instead. The damper ends up representing the internal losses of the spring. The damper adds a dash of reality to the system, and will make the mass eventually stop moving just like in real life.

The viscous damping force equation is similar to the spring force equation:

**F _{damping}** = -b

Instead of using the displacement like we did with Hooke's law, we're using the velocity. Instead of the spring constant we have -b, called the "viscous damping coefficient", measured in kg / s. Again, we have the negative sign, which signifies that the force acts *opposite* the velocity. If you're moving one direction, damping will slow you down by pulling in the opposite direction.

Additionally, if by some external means, you wiggle the object at that very frequency, you can cause it to vibrate *wildly.* That's what happens when an opera singer breaks a glass with her voice -- she's singing that frequency and therefore "exciting" the glass at its natural frequency. More impressive is the Tacoma Narrows Bridge Collapse Disaster, caused by the wind exciting the bridge's natural frequency. Jump to 1 minute for the oscillation, 3 minutes for the collapse.

If you know the spring stiffness and mass of a spring-mass system, you can calculate the natural frequency. The natural frequency is

*f*_{n} = ( 1 / 2 π ) * sqrt( k / m )

If there's a damper attached to the system, that changes the natural frequency slightly.

If you use external motion to excite a spring-mass-damper system (called forced vibration), the following effects occur:

- If the external frequency is lower than the natural frequency, the mass will move more or less with the external "shaker"
- If the external frequency is near the natural frequency, the mass will move much farther from end to end than the external shaker (think of pushing somebody on a swing), but the mass will also be 90 degrees out of phase with the shaker.
- If the external frequency is higher than the natural frequency, the mass will move less far than the shaker, and will also be 180 degrees out of phase with the shaker (ie, moving in the opposite direction).

```
/* Spring stiffness, in kg / s^2 */
var k = -20;
var spring_length = 180;
/* Damping constant, in kg / s */
var b = -0.5;
/* Block position and velocity. */
var block = {x: 100, v: 0, mass: 0.5};
var wall = {x: 30, lx: 30, v: 0, t: 0, frequency: 0};
```

Some of the usual setup above. We create a block object and a wall object. We set a spring_length (for the spring's equilibrium length), and initialize the spring constant and the damping constant.

Inside our loop:

```
var loop = function() {
/* Move the wall. */
wall.t += frameRate;
wall.lx = wall.x;
wall.x = 30 + 70 * Math.sin(2 * Math.PI * wall.frequency * wall.t);
wall.v = (wall.x - wall.lx) / frameRate;
/* Loop continues .... */
```

In our example, the spring and damper are connected to a moveable wall on one end and a block on the other end. The code above moves the wall according to the sine function.

```
/* ... continued from above . */
/* Move the block. */
if ( ! mouse.isDown )
{
var F_spring = k * ( (block.x - wall.x) - spring_length );
var F_damper = b * ( block.v - wall.v );
var a = ( F_spring + F_damper ) / block.mass;
block.v += a * frameRate;
block.x += block.v * frameRate;
}
```

There's not too much magic here. We learned how to use forces in the Gravity and Drag article before this one.

We first calculate the spring force by figuring out the spring displacement: the distance between the wall and block at this moment minus the equilibrium length of the spring. Then we multiply that by the spring constant, which is a negative number.

The damping force is calculated similarly, except using the velocities of the wall and block instead of position.

Not shown is a bunch of code to draw the wall and block. There's also some mouse handling: in this example, you can grab the block with the mouse.

In order to get a good feel for what goes on with spring-mass-damper systems, please try the following procedure:

- Grab the block with the mouse, pull it to the side, and let go. The block will oscillate and die out.
- Increase stiffness to -60 kg / s
^{2}, decrease damping to 0 and pluck the block. The block will oscillate (almost) forever. It won't go forever because of the mathematical solving technique we're using -- more on that next week! - Increase damping to -10 kg / s, pluck the block. There should be no oscillation.
- Set the following: stiffness = -15, damping = -0.3, mass = 0.2
- Set the frequency to 0.5 Hz -- observe that the mass moves more or less with the wall
- Set the frequency to 1.5 Hz -- observe the wild resonant oscillation
- Set the frequency to 3.0 Hz -- observe that the mass moves less than the wall, and also in the opposite direction

What does this mean for a car suspension? Imagine the wall as the road and wheel, and the mass as the rest of the car. If you drive slowly over big, loping bumps, the whole car moves up and down. If you drive quickly over rapid bumps, the tire will bounce up and down a lot but the car will stay more or less in place.

Next week we'll be talking about different methods of solving our equations, and hopefully get something that feels a little smoother.

Here's the JSFiddle:

This is the first post in the Modeling Physics in Javascript series. As such, we'll need to cover some introductory material. There are some of you who have real training in physics and calculus. You may be tempted to scream "that's not the whole story" at me when

]]>This is the first post in the Modeling Physics in Javascript series. As such, we'll need to cover some introductory material. There are some of you who have real training in physics and calculus. You may be tempted to scream "that's not the whole story" at me when I explain some concepts, and my response to you is this: I wish I could cover all the amazing parts of physics and calculus in one blog post, but I can't. I'll therefore cover only the bits I need. Hopefully, the people reading this will accidentally learn physics while trying to pick up some cool JS tricks.

Yes, there's a JSFiddle to play with at the bottom of the page!

Not too shabby for day 1! We'll first talk about Newton's 2nd Law, forces, gravity, and a touch of calculus before we can start coding.

Newton's 2nd Law looks like this: F = ma.

Well, not quite. It looks more like this: **F _{net}** = m

As you can imagine, physics has a manner of starting simple and then getting very complicated very quickly. The subscript "net" means that the "F" doesn't just refer to a single force, but the sum total of all forces on the object. The bold "F" and "a" mean that those variables (force and acceleration) are vectors -- meaning that they exist separately in 3 different directions (X, Y, and Z).

But that's not too bad. If you don't want to do vector math, you can simply rewrite **F _{net}** = m

- F
_{x, net}= ma_{x} - F
_{y, net}= ma_{y} - F
_{z, net}= ma_{z}

Let's just jump into a simple example. You have a ball with a mass of 2 kg, and there are three forces acting on it:

- 2 Newtons pulling right
- 4 N pulling left
- 1 N pulling down

And since there's only one force acting in the Y direction, the F_{y, net} is just -1 N. (Let's say "up" is positive and "down" is negative -- but **only for now**. We'll switch that up later. In general, you use positive and negative signs in a way that makes sense for your specific problem.)

Finally, since our ball weighs 2 kg, we can substitute our numbers into F = ma and get the following two equations:

- -2 N = 2 kg * a
_{x} - -1 N = 2 kg * a
_{y}

- a
_{x}= -2 N / 2 kg - a
_{y}= -1 N / 2 kg

- a
_{x}= -1 m / s^{2} - a
_{y}= -0.5 m / s^{2}

So we had a situation where we know the mass of an object and the forces acting on it. We added up the forces (assigning negative signs to "left" and "down", causing those forces to subtract instead), and rearranged to solve for acceleration -- and we did this for both the X and the Y directions separately. In this example, the ball is accelerating down and to the left, but it's accelerating more to the left than it is downwards.

(More advanced: sometimes you don't know the X and Y components of a force. It's possible that you only know about *one* force that's angled at, say, 30 degrees up from right. In that case, you can use cosine and sine to figure out the X and Y pieces of that force respectively. We'll do that in a future article.)

If our ball from above (that we already solved for) is on Earth and experiencing gravity, then we just need to modify the a_{y} equation slightly. We'll take the downward acceleration that the force is causing and combine it with the downward acceleration that gravity causes:

a_{y} = -0.5 m / s^{2} - 9.8 m / s^{2}

That leaves us with an acceleration of

a_{y} = -10.3 m / s^{2}

As you can see, the downward force combined with the acceleration from gravity shoots the ball downward even faster than either gravity or the force alone could.

So, gravity is simple (if you're on a planet). All you do is modify the a_{y} acceleration to factor in the downward pull of gravity.

In a future article we'll look at how to model gravity if you're *not* on a planet (perhaps you *are* a planet), but that doesn't come until later...

Our ball experiences gravity, but as I mentioned, we don't need to model that as a force; we just plug it directly into the acceleration result. Drag, however, *is* a force, and we'll have to model it.

The equation (one of the equations) for aerodynamic drag looks like this:

**F _{D}** = -0.5 * C

It looks complicated, but when we break it down, it's pretty simple. First off, notice the bold characters. Like F = ma above, a bold variable means it's actually a vector -- so right off the bat we can split this into two equations:

- F
_{D, x}= -0.5 * C_{D}* A * ρ * v_{x}^{2} - F
_{D, y}= -0.5 * C_{D}* A * ρ * v_{y}^{2}

And then we look at each one of those terms above:

- C
_{D}is the "coefficient of drag", which is influenced by the shape of the object (and a little bit by its material). For a ball, this is 0.47, and is a dimensionless quantity. - A is the frontal area or frontal projection of the object. If you look at a silhouette of the object from the front, this is the area of that shape. For a ball, the frontal area is just the area of a circle, or π r
^{2}. - ρ (Greek letter rho) is the density of the fluid the ball is in. If our ball's in air, this value is 1.22 (kg / m
^{3}) - Velocity squared -- since we're looking at this in two directions separately, we use the X velocity and the Y velocity respectively.
- Note the -0.5 at the beginning. The negative sign, with the fact that the equation uses velocity, indicates that this force pushes
*in the opposite direction the ball is moving*at all times. Because the velocity is squared it'll always be positive, which means the whole equation will always be negative, ie, opposite the velocity.

Calculus, like physics, is amazing and has a wonderful depth that I can't do justice in a blog post.

The "derivative" in calculus describes how something changes as something else is changing; often this will be called the "rate of change". When you drive a car at 30 MPH, your position is changing by 30 miles every hour. Your position changes as time changes. It can then be said that velocity is the "derivative of position with respect to time" or simply the "time derivative of position".

Then we can think about what happens when you speed up or slow down (accelerate). You might change your *velocity* by 5 MPH per hour (MPHPH?). In that sense, your velocity is changing with time, and you can say that acceleration is the time derivative of velocity.

So it starts with position. The derivative of position is velocity. And the derivative of velocity is acceleration. (The derivative of acceleration is called "jerk", and the derivative of jerk is called "jounce".)

Why is this relevant? Because if you know the acceleration of something (5 meters per second per second), and if you know how fast it's going when you start looking at it (let's say it's not moving at all), you can figure out *where* it will be at every moment in the future.

An example: your ball is accelerating at 2 m / s^{2} (meters per second per second). Let's say it's not moving at all when you start looking at it, and that the starting point is called x = 0;

Time | Accel | Velocity | Position |
---|---|---|---|

0 s | 2 m / s^{2} |
0 m / s | 0 m |

1 s | 2 m / s^{2} |
2 m / s | 0 m |

2 s | 2 m / s^{2} |
4 m / s | 2 m |

3 s | 2 m / s^{2} |
6 m / s | 6 m |

4 s | 2 m / s^{2} |
8 m / s | 12 m |

5 s | 2 m / s^{2} |
10 m / s | 20 m |

6 s | 2 m / s^{2} |
12 m / s | 30 m |

And so on. This is the approach we'll use when solving for the motion of our ball, except we'll do it not once per second but 40 times per second. All we're doing is using our knowledge of the forces to figure out the acceleration at every frame. Then we use the acceleration and current velocity to figure out the new velocity. And then we use the velocity and last position to find the current position.

Time to dive in. I won't reproduce all the code in snippets, because there's some stuff that has nothing to do with physics. You'll be able to see the full script at the bottom of the page in the JSFiddle.

```
var frameRate = 1/40; // Seconds
var frameDelay = frameRate * 1000; // ms
var loopTimer = false;
var ball = {
position: {x: width/2, y: 0},
velocity: {x: 10, y: 0},
mass: 0.1, //kg
radius: 15, // 1px = 1cm
restitution: -0.7
};
var Cd = 0.47; // Dimensionless
var rho = 1.22; // kg / m^3
var A = Math.PI * ball.radius * ball.radius / (10000);
var ag = 9.81;
```

We set up the frame rate and plug in some physics values. We also create a ball object that stores the ball's position, velocity, mass, radius, and a number called "restitution". You'll see later that this value determines how bouncy the ball is.

Notice here that we've set the ball to be moving at the start of the simulation.

The best part of programming real physics is the fact that you can look up the density of water and replace the value for rho, and the ball will actually behave as if it's in water! If you program the physics correctly, then all you have to do is change the constants and the rest follows. Want the ball to be on the moon? Just change the acceleration due to gravity. Want the ball to swim through water? Just change the density rho. Want a light, floaty beach ball? Lower the mass and increase the radius.

*Please play with these values* in the JSFiddle below. Change rho and the radius and the mass, and see how physics affects the simulation!

```
var setup = function() {
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
canvas.onmousemove = getMousePosition;
canvas.onmousedown = mouseDown;
canvas.onmouseup = mouseUp;
ctx.fillStyle = 'red';
ctx.strokeStyle = '#000000';
loopTimer = setInterval(loop, frameDelay);
}
```

The setup function initializes the canvas and sets up a loop that executes every frameDelay milliseconds. We'll do all the physics and animation in the loop function.

In the loop:

```
// Do physics
// Drag force: Fd = -1/2 * Cd * A * rho * v * v
var Fx = -0.5 * Cd * A * rho * ball.velocity.x * ball.velocity.x * ball.velocity.x / Math.abs(ball.velocity.x);
var Fy = -0.5 * Cd * A * rho * ball.velocity.y * ball.velocity.y * ball.velocity.y / Math.abs(ball.velocity.y);
Fx = (isNaN(Fx) ? 0 : Fx);
Fy = (isNaN(Fy) ? 0 : Fy);
// Calculate acceleration ( F = ma )
var ax = Fx / ball.mass;
var ay = ag + (Fy / ball.mass);
// Integrate to get velocity
ball.velocity.x += ax*frameRate;
ball.velocity.y += ay*frameRate;
// Integrate to get position
ball.position.x += ball.velocity.x*frameRate*100;
ball.position.y += ball.velocity.y*frameRate*100;
```

First off, we calculate the drag forces on the ball. There's a little trick I used to get the direction of the velocity. Instead of using "if" statements to see if the velocity is positive or negative, I just do:

```
ball.velocity.y / Math.abs(ball.velocity.y)
```

at the end of the drag force statements. Dividing a number by its absolute value just leaves the sign. Other than that, the drag force lines are pretty straightforward. We're just calculating the forces.

After that, we calculate acceleration. Notice that the statement for "ay" is different from "ax". Gravity only works in the Y direction, so we add that in here. Also notice that in this problem, "downwards" is positive, unlike the example at the top of the page.

After that, we update the ball velocities with the acceleration times the frame rate. The reason we multiply by the frame rate is so: the acceleration is given in "meters per *second*-squared". But we're calling this loop 40 times a second (not once a second), so we need to divide by 40 (or multiply by 1/40 in this case) to adjust for the frame rate.

Finally, update the ball positions in a similar fashion. In this case we're also multiplying by 100. If you look at the ball object definition way above you'll see I commented that "1px = 1cm", so this *100 is just an adjustment to make everything work out in meters.

Then we handle collisions with the walls:

```
// Handle collisions
if (ball.position.y > height - ball.radius) {
ball.velocity.y *= ball.restitution;
ball.position.y = height - ball.radius;
}
if (ball.position.x > width - ball.radius) {
ball.velocity.x *= ball.restitution;
ball.position.x = width - ball.radius;
}
if (ball.position.x < ball.radius) {
ball.velocity.x *= ball.restitution;
ball.position.x = ball.radius;
}
```

We're just checking to see if the ball has ended up past the wall in this frame. If it has, then we multiply the velocity in that direction by the restitution coefficient from above. Since that number is always negative, it'll make the ball reverse direction. If you set the restitution to -1, it'll be perfectly bouncy, meaning it'll bounce up as high as it started falling from. If you set the restitution to 0, it'll flop dead on the ground with no bounce whatsoever. And if you set it to something like -2, it'll bounce even higher than it started. Play with it!

We also modify the position of the ball to just kiss the wall -- this way the ball won't get stuck "in" the wall. Keep in mind that the ball is moving in discrete motions, and so when it collides with the wall it's actually overlapping slightly.

Finally, since we want to be able to control the ball with the mouse, we'll add some handlers (not all code shown here):

```
var mouseDown = function(e) {
if (e.which == 1) {
getMousePosition(e);
mouse.isDown = true;
ball.position.x = mouse.x;
ball.position.y = mouse.y;
}
}
var mouseUp = function(e) {
if (e.which == 1) {
mouse.isDown = false;
ball.velocity.y = (ball.position.y - mouse.y) / 10;
ball.velocity.x = (ball.position.x - mouse.x) / 10;
}
}
```

If you click and drag the mouse, and let go, you'll create a kind of slingshot effect. This is achieved not by applying a force to the ball (which you could do), but rather by overriding the velocity of the ball based on how far you pulled the mouse. I like this approach better because it's easier to apply than a force. If you were to use a force to move the ball with the mouse, you'd have to apply the force over a period of time. The "initial velocity" technique above just lets you un-naturally override the velocity in an instant and let physics figure everything out again.

I hope you learned something! Please fork and play with the code in the fiddle below. Click and drag the mouse to slingshot the ball.

Note that certain configurations of variables will cause the simulation to become unstable. Try setting rho = 1000 but leaving the mass at 0.1. The ball should spaz out and blink around the screen. This isn't a problem with the physics, it's just that we're not running at a high enough frame rate for the very large drag forces. To solve that problem we would have to increase the frame rate to make the simulation stable again. Or we could use a different solver (we're using Euler's method here, a first-degree ODE solver) -- but we won't talk about solvers for a few weeks.

Physics in Javascript Table of Contents:

Another post that starts with "I love":

I love physics. I really do. Once upon a time I was a real engineer (Master in Mechanical Engineering, hybrid car

]]>Physics in Javascript Table of Contents:

Another post that starts with "I love":

I love physics. I really do. Once upon a time I was a real engineer (Master in Mechanical Engineering, hybrid car design, control systems, sustainable energy, etc etc etc) but decided to go back to the software world. Regardless, I still can't get physics out of my head. I read textbooks on quantum mechanics regularly. It's a sickness.

The great thing about physics is that it's not too hard. Well, maybe it is, but once you understand a handful of core concepts, you can do tons of problems. If you can figure out how a ball moves under the influence of gravity, you can also model the motion of a car's suspension. While that sounds like a big stretch, it's really not: it's all tied together by a few basic concepts.

I also enjoy Javascript. I'm not a graphics programmer, and have no knowledge of OpenGL or WebGL, but I like Javascript especially because it controls the fancy HTML5 canvas element.

And, if you can combine your rudimentary knowledge of physics with your rudimentary knowledge of Javascript, you can build **really cool physics models and simulations.**

With this series, I'm going to teach you how to model physics. We'll use Javascript to do the math and draw the animations to the canvas.

We'll start simple, with a bouncy ball and gravity, and we'll eventually move on to modeling full systems. It's going to be fun. While it'll start slow, I want to end up modeling things like bipedal robots within a couple dozen posts. And you'll be learning physics in the process.

Buckle up. Here's an example of a grandfather clock that actually simulates *real physics *for the swinging pendulum -- just to whet your appetite:

(PS: the physics in the below example is a little bit fudged, because it was a code-debugging example I used for a class I used to teach; please wait for the full article on the pendulum clock before trying to follow the physics!)

]]>