<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:media="http://search.yahoo.com/mrss/"><channel><title><![CDATA[Physics - Burak Kanber, Engineer]]></title><description><![CDATA[Author, tech CTO, engineer, and some other things too.]]></description><link>https://burakkanber.com/</link><image><url>https://burakkanber.com/favicon.png</url><title>Physics - Burak Kanber, Engineer</title><link>https://burakkanber.com/</link></image><generator>Ghost 2.19</generator><lastBuildDate>Wed, 28 Aug 2024 17:26:35 GMT</lastBuildDate><atom:link href="https://burakkanber.com/tag/physics/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[Physics in Javascript: Rigid Bodies -- Part 1 (Pendulum Clock)]]></title><description><![CDATA[<!--kg-card-begin: markdown--><!--kg-card-begin: markdown--><p>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.</p>
<!-- more -->
<blockquote>
<p>This article is part of the</p></blockquote>]]></description><link>https://burakkanber.com/blog/physics-in-javascript-rigid-bodies-part-1-pendulum-clock/</link><guid isPermaLink="false">59b43b8b934a21000178fc1c</guid><category><![CDATA[Physics]]></category><dc:creator><![CDATA[Burak Kanber]]></dc:creator><pubDate>Wed, 03 Oct 2012 16:00:00 GMT</pubDate><content:encoded><![CDATA[<!--kg-card-begin: markdown--><!--kg-card-begin: markdown--><p>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.</p>
<!-- more -->
<blockquote>
<p>This article is part of the <a title="Modeling Physics in Javascript: Introduction" href="http://burakkanber.com/blog/modeling-physics-in-javascript-introduction/" target="_blank">Physics in Javascript</a> series. If you feel lost reading this article, you may want to read the <a title="Modeling Physics in Javascript: Gravity and Drag" href="http://burakkanber.com/blog/modeling-physics-javascript-gravity-and-drag/" target="_blank">Gravity and Drag</a> and <a title="Physics in Javascript: Car Suspension – Part 1 (Spring, Mass, Damper)" href="http://burakkanber.com/blog/physics-in-javascript-car-suspension-part-1-spring-mass-damper/" target="_blank">Spring-Mass-Damper</a> articles.</p>
</blockquote>
<blockquote>
<p>Just looking for the <a href="#jsfiddle">cool JSFiddle code example</a>?</p>
</blockquote>
<p>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.</p>
<p>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).</p>
<p>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.</p>
<h2 dir="ltr">Translation and Rotation</h2>
Let's start by comparing linear motion (translation) to angular motion (rotation). Translation has properties that we’re pretty familiar with by now: position, velocity, acceleration, mass, and force. Rotation is similar, but the variables have been modified slightly to: angle, angular velocity, angular acceleration, moment of inertia, and torque. Let’s introduce these concepts very briefly.
<h3 dir="ltr">Angle</h3>
Analogous to “position” for translation, the angle describes the current orientation of a rigid body. If you’re working in two dimensions -- as we are here -- you only need one angle to fully describe an object’s rotation. Typically, angle is denoted by the Greek letter theta: θ. In three dimensions, three angles are required to describe the object’s orientation, and in that case you should use <a href="http://en.wikipedia.org/wiki/Euler_angles" target="_blank">Euler angles</a>. Angle is a dimensionless quantity typically measured in radians or degrees. This is in contrast to the “position” in linear motion, whose dimension is “length”.
<p>Concretely: the angle θ is the number of radians or degrees something is rotated by.</p>
<h3 dir="ltr">Angular Velocity and Angular Acceleration</h3>
Like linear velocity, angular velocity describes how much the object’s angle changes in a given time-frame. While “degrees per hour” is an acceptable unit, angular velocity is almost always given in “radians per second”. Since radians are dimensionless, angular velocity has a dimension of inverse time. Typically, the Greek letter omega is used for angular velocity: ω.
<p>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: α.</p>
<h3 dir="ltr">Torque</h3>
Force, in the linear world, is directly responsible for an object’s acceleration. Rotation is no different; in the angular world, torque is responsible for an object's angular acceleration.
<p>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.</p>
<p>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!).</p>
<p>Torque is measured in units of force times distance: newton-meters or pound-feet, and is typically denoted by the Greek letter tau: τ.</p>
<h3 dir="ltr">Moment of Inertia</h3>
The toughest piece of the rotational puzzle to calculate from scratch is the moment of inertia. In linear motion, mass (inertia) is a sort of resistance to changing the object’s motion. A light object is easier to speed up or slow down than a heavy object. Similarly, moment of inertia is a resistance to a change in rotation. But moment of inertia is more complicated than mass, because both the object’s mass and its shape and size need to be considered. A 5 pound hoop is harder to get spinning than a 5 pound disc of the same size, because the hoop has all its mass near the edge.
<p>The moment of inertia is given in units of kg * m<sup>2</sup> (kilogram times meters squared) and is typically denoted by the capital letter I or J. I like J.</p>
<p>Fortunately, you can just <a href="http://en.wikipedia.org/wiki/List_of_moments_of_inertia" target="_blank">look up the moments of inertia of many common shapes</a> 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.</p>
<h3 dir="ltr">Equation of Motion and a Pendulum Clock</h3>
Newton’s 2nd Law is <strong>F<sub>net</sub></strong> = m*<strong>a</strong>. Modified for rotation, we can write it as <strong>τ<sub>net</sub></strong> = J*<strong>α</strong>. Notice that, like the linear form of the equation, both τ and α are vectors. Since our example is in 2D -- which means all our rotation happens around the "z" axis -- we can just assume these are scalars for now.
<p>Since you’ve certainly read the <a title="Modeling Physics in Javascript: Gravity and Drag" href="http://burakkanber.com/blog/modeling-physics-javascript-gravity-and-drag/" target="_blank">Gravity and Drag</a> and <a title="Physics in Javascript: Car Suspension – Part 1 (Spring, Mass, Damper)" href="http://burakkanber.com/blog/physics-in-javascript-car-suspension-part-1-spring-mass-damper/" target="_blank">Spring-Mass-Damper</a> 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 &quot;figure out the net torque&quot; step, especially if you're uncomfortable with trigonometry. Let’s dive into an example.</p>
<blockquote>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!</blockquote>
<h2>Pendulum Clock</h2>
I want to build a simple and elegant animated pendulum clock. Rather than just "fudging" the motion of the pendulum by using sine easing, I want to solve for the physics directly. (Though physics students will recognize that sine actually <em>is</em> the solution to this problem!)
<p>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.</p>
<p>Diving right into some code:</p>
<pre><code class="language-javascript">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;
...
}
</code></pre>
<p>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.</p>
<p>Then we calculate the value of the pendulum's moment of inertia. Our <a href="http://en.wikipedia.org/wiki/List_of_moments_of_inertia" target="_blank">Wikipedia list of moments of inertia</a> tells us that a &quot;point mass m at distance r from the axis of rotation&quot; has a moment of inertia of m*r<sup>2</sup>, so that's what we use.</p>
<h2>Velocity Verlet</h2>
I've done a few things differently in this code example. First of all, I've used <code>requestAnimFrame()</code> instead of <code>setInterval()</code> (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 <a href="http://en.wikipedia.org/wiki/Verlet_integration#Velocity_Verlet" target="_blank">velocity verlet method</a>.
<p>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!</p>
<p><a href="http://en.wikipedia.org/w/index.php?title=File:RightRiemann2.svg&amp;page=1"><img src="http://upload.wikimedia.org/wikipedia/commons/thumb/4/45/RightRiemann2.svg/600px-RightRiemann2.svg.png" alt="File:RightRiemann2.svg" width="420" height="336"></a></p>
<p>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 <a href="http://en.wikipedia.org/wiki/Riemann_sum" target="_blank">Riemann sum</a>); 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.</p>
<p>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 <a href="http://en.wikipedia.org/wiki/Midpoint_method" target="_blank">midpoint method</a>. There's also the <a href="http://en.wikipedia.org/wiki/Trapezoidal_rule" target="_blank">trapezoidal method</a>, which draws trapezoids instead of rectangles. There's also the very accurate <a href="http://en.wikipedia.org/wiki/Runge%E2%80%93Kutta_methods" target="_blank">Runge-Kutta method</a>, which uses a weighted average of 4 points along the function to calculate the area below the curve.</p>
<p>Here's a nice demonstration of how much better the midpoint method (in green) works compared to Euler's method (blue).</p>
<p><a href="http://en.wikipedia.org/wiki/File:Numerical_integration_illustration,_h%3D1.png"><img src="http://upload.wikimedia.org/wikipedia/commons/thumb/b/b5/Numerical_integration_illustration%2C_h%3D1.png/412px-Numerical_integration_illustration%2C_h%3D1.png" alt="File:Numerical integration illustration, h=1.png" width="412" height="600"></a> Source: Wikipedia[/caption]</p>
<p>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!</p>
<h2>The Loop</h2>
Let's get back to code. In the loop (boring stuff omitted):
<pre><code class="language-javascript">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);
...
};
</code></pre>
<p>The velocity verlet method has us do things &quot;out of order&quot;, so to speak. I'll describe the steps in the order I feel is natural, however, starting with torque:</p>
<p>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<sup>2</sup>, the acceleration due to gravity on Earth).</p>
<p>Since we're looking for a torque, we have to multiply that perpendicular force by its distance from the center.</p>
<p>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.</p>
<p>Finally, we calculate the angle θ. Notice this time I kept the 0.5 * α * Δt<sup>2</sup> 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!</p>
<p>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.</p>
<p>As an added bonus, we draw a cute little clock. See the JSFiddle for details.</p>
<h2>Results</h2>
If you have a formal education in physics, you've probably done this very same pendulum problem by hand. You should notice that our numerical solution agrees very well with the analytical solution. For one, the mass of the pendulum has no effect on the pendulum's period. Only the length matters! Additionally -- without any damping -- the pendulum always returns to its highest points on either side. Feel free to fork the code below and play around.
<p>If you like these articles please tell your friends, please sign up for the mailing list below, and consider <a href="https://twitter.com/bkanber" target="_blank">following me on Twitter</a>. 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!</p>
<p>You may also like my <a href="http://burakkanber.com/blog/machine-learning-in-other-languages-introduction/" target="_blank">Machine Learning in Javascript</a> series.</p>
<iframe id="jsfiddle" style="width: 100%; height: 700px; border: 1px solid #CCC;" src="https://jsfiddle.net/uvYw5/342/embedded/result,js,html,css/" frameborder="0" width="320" height="240"></iframe>
<!-- Begin MailChimp Signup Form -->
<link href="http://cdn-images.mailchimp.com/embedcode/classic-081711.css" rel="stylesheet" type="text/css">
<style type="text/css">
	#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
	#mc_embed_signup form { padding: 0 }
</style>
<div id="mc_embed_signup">
<form action="http://burakkanber.us5.list-manage.com/subscribe/post?u=3269dc566d381f05852d92aa8&amp;id=73795f99d0" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate="">
	<h2>Email me when new Physics in JS articles are written</h2>
<div class="mc-field-group">
	<label for="mce-EMAIL">Email Address </label><input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL">
</div>
<div class="mc-field-group input-group">
    <strong>Survey: would you buy a Physics in JS e-book? </strong>
    <input type="checkbox" value="1" name="group[6713][1]" id="mce-group[6713]-6713-0"><label for="mce-group[6713]-6713-0">I would pay $10 for a DRM-free e-book with tons of Physics in JS.</label>
</div>
<div id="mce-responses" class="clear">
<div class="response" id="mce-error-response" style="display:none"></div>
<div class="response" id="mce-success-response" style="display:none"></div>
</div>	<div class="clear"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
</form>
</div>
<!--End mc_embed_signup--><!--kg-card-end: markdown--><!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Physics in Javascript: Car Suspension - Part 1 (Spring, Mass, Damper)]]></title><description><![CDATA[<!--kg-card-begin: markdown--><!--kg-card-begin: markdown--><p>Our big project -- our goal -- for this mechanics/dynamics portion of <a title="Modeling Physics in Javascript: Introduction" href="http://burakkanber.com/blog/modeling-physics-in-javascript-introduction/">Modeling Physics in Javascript</a> 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</p>]]></description><link>https://burakkanber.com/blog/physics-in-javascript-car-suspension-part-1-spring-mass-damper/</link><guid isPermaLink="false">59b43b8b934a21000178fc1e</guid><category><![CDATA[Physics]]></category><dc:creator><![CDATA[Burak Kanber]]></dc:creator><pubDate>Mon, 10 Sep 2012 16:00:00 GMT</pubDate><content:encoded><![CDATA[<!--kg-card-begin: markdown--><!--kg-card-begin: markdown--><p>Our big project -- our goal -- for this mechanics/dynamics portion of <a title="Modeling Physics in Javascript: Introduction" href="http://burakkanber.com/blog/modeling-physics-in-javascript-introduction/">Modeling Physics in Javascript</a> 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.</p>
<!-- more -->
<p>Today, we'll be talking about arguably the most important set of building blocks there is: the spring-mass-damper.</p>
<p>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.</p>
<h2>The Spring and Hooke's Law</h2>
The humble spring is one of the three most important mechanical components to know how to model. Why is the spring so important? How often do you actually see a spring? Sure, they're in lots of mechanical devices, like your car and your door lock and your clicky pen, but it turns out that they're a lot more important than their use in mechanical devices.
<p>The reason springs are so important is because there's nothing in the real universe that's &quot;infinitely rigid&quot;. Every object in the universe is a little bit springy, even if you can't tell by eye.</p>
<p>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 <em>not </em>start moving the instant you start moving your hand. There's a tiny delay -- a fraction of a second -- before the cup starts moving.</p>
<p>That's because the stick isn't &quot;infinitely rigid&quot; -- 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.</p>
<p>(By the way, the speed of that shockwave is called the &quot;speed of sound&quot;, and every different material has a different speed of sound.)</p>
<p>Back to the stick: it's really a spring; a very, very stiff spring (the term &quot;stiffness&quot; actually refers to something slightly different, but for this article I'll use &quot;stiffness&quot; and &quot;spring constant&quot; 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 <em>does </em>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.</p>
<p>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.</p>
<p>Fortunately for us, the basic method of modeling springs is really easy. It's governed by Hooke's Law, which says this:</p>
<p><strong>F<sub>spring</sub></strong> = -k<strong>Δx</strong></p>
<p>The force that a spring pushes or pulls with is -k (called the &quot;spring constant&quot;, measured in kg / s<sup>2</sup>) times the displacement. Let's look a little closer:</p>
<p>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 &quot;equilibrium length&quot; or &quot;natural length&quot;), but it's being crushed to 8 inches, the displacement is 2 inches.</p>
<p>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 &quot;k&quot; changes due to things like temperature and if the spring is stretched to an extreme, but the assumption that &quot;k&quot; is a constant is usually a good one. There are also springs designed to have a non-constant &quot;k&quot;, but we'll avoid those too.</p>
<p>The spring constant is also negative; that implies that the spring force <em>fights</em> 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.</p>
<p>In short: a spring <em>resists changes in displacement.</em></p>
<h2>Dashpots and Viscous Damping</h2>
While a spring resists changes in displacement, a damper resists velocity. A spring wants to go back to position 0, while a damper wants to go back to velocity 0. Physically dampers can take many forms, but the one we typically talk about is called a dashpot. The dashpot is a cylinder filled with fluid with a piston that can move through the liquid. You can move the piston through the liquid, but you experience considerable resistance in doing so. <a href="http://en.wikipedia.org/wiki/Dashpot" target="_blank">Check out the Wikipedia article for a nice image</a>.
<p>Why are dampers so important? Just like springs, <em>actual</em> dampers are not used everywhere (in cars we call them &quot;shock absorbers&quot;), but the mathematic model <em>is</em> seen everywhere. Dampers often represent the internal frictional losses of a system.</p>
<p>Mathematically, if you had just a perfect mass and a perfect spring and &quot;plucked&quot; it in a vacuum, the mass would oscillate back and forth <em>forever</em>, 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.</p>
<p>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 (&quot;ideal&quot;), 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.</p>
<p>The viscous damping force equation is similar to the spring force equation:</p>
<p><strong>F<sub>damping</sub></strong> = -b<strong>v</strong></p>
<p>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 &quot;viscous damping coefficient&quot;, measured in kg / s. Again, we have the negative sign, which signifies that the force acts <em>opposite</em> the velocity. If you're moving one direction, damping will slow you down by pulling in the opposite direction.</p>
<h2>Resonant Frequency</h2>
Together, the spring, mass and damper elements form what's called a harmonic oscillator, and that system has some interesting properties: most notably, a "resonant frequency" (or natural frequency). If you've ever whacked a knife against a table, or tapped a wine glass with a fork and listened to it ring, you've listened to a resonant frequency. Because of the springiness of all materials, every object in the world has some frequency that it "likes". If you tap the object, it'll resonate at its so-called "natural frequency".
<p>Additionally, if by some external means, you wiggle the object at that very frequency, you can cause it to vibrate <em>wildly.</em> That's what happens when an opera singer breaks a glass with her voice -- she's singing that frequency and therefore &quot;exciting&quot; the glass at its natural frequency. More impressive is the <a href="http://www.youtube.com/watch?v=3mclp9QmCGs" target="_blank">Tacoma Narrows Bridge Collapse Disaster</a>, caused by the wind exciting the bridge's natural frequency. Jump to 1 minute for the oscillation, 3 minutes for the collapse.</p>
<p>If you know the spring stiffness and mass of a spring-mass system, you can calculate the natural frequency. The natural frequency is</p>
<p><em>f</em><sub>n</sub> = ( 1 / 2 π ) * sqrt( k / m )</p>
<p>If there's a damper attached to the system, that changes the natural frequency slightly.</p>
<p>If you use external motion to excite a spring-mass-damper system (called forced vibration), the following effects occur:</p>
<ul>
	<li>If the external frequency is lower than the natural frequency, the mass will move more or less with the external "shaker"</li>
	<li>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.</li>
	<li>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).</li>
</ul>
Let's build the code and play with this, so we can finally see these effects in action!
<h2>The Code</h2>
<pre><code class="language-javascript">/* 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};
</code></pre>
<p>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.</p>
<p>Inside our loop:</p>
<pre><code class="language-javascript">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 .... */
</code></pre>
<p>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.</p>
<pre><code class="language-javascript">	/* ... 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;
	}
</code></pre>
<p>There's not too much magic here. We learned how to use forces in the <a title="Modeling Physics in Javascript: Gravity and Drag" href="http://burakkanber.com/blog/modeling-physics-javascript-gravity-and-drag/">Gravity and Drag</a> article before this one.</p>
<p>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.</p>
<p>The damping force is calculated similarly, except using the velocities of the wall and block instead of position.</p>
<p>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.</p>
<p>In order to get a good feel for what goes on with spring-mass-damper systems, please try the following procedure:</p>
<ul>
	<li>Grab the block with the mouse, pull it to the side, and let go. The block will oscillate and die out.</li>
	<li>Increase stiffness to -60 kg / s<sup>2</sup>, 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!</li>
	<li>Increase damping to -10 kg / s, pluck the block. There should be no oscillation.</li>
	<li>Set the following: stiffness = -15, damping = -0.3, mass = 0.2</li>
	<li>Set the frequency to 0.5 Hz -- observe that the mass moves more or less with the wall</li>
	<li>Set the frequency to 1.5 Hz -- observe the wild resonant oscillation</li>
	<li>Set the frequency to 3.0 Hz -- observe that the mass moves less than the wall, and also in the opposite direction</li>
</ul>
<p>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.</p>
<p>Next week we'll be talking about different methods of solving our equations, and hopefully get something that feels a little smoother.</p>
<p>Here's the JSFiddle:</p>
<iframe style="width: 100%; height: 450px; border: 1px solid #CCC;" src="https://jsfiddle.net/bkanber/pDngH/embedded/result,js,html,css/" frameborder="0"></iframe>
<!-- Begin MailChimp Signup Form -->
<link href="http://cdn-images.mailchimp.com/embedcode/classic-081711.css" rel="stylesheet" type="text/css">
<style type="text/css">
	#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
	#mc_embed_signup form { padding: 0 }
</style>
<div id="mc_embed_signup">
<form action="http://burakkanber.us5.list-manage.com/subscribe/post?u=3269dc566d381f05852d92aa8&amp;id=73795f99d0" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate="">
	<h2>Email me when new Physics in JS articles are written</h2>
<div class="mc-field-group">
	<label for="mce-EMAIL">Email Address </label><input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL">
</div>
<div class="mc-field-group input-group">
    <strong>Survey: would you buy a Physics in JS e-book? </strong>
    <input type="checkbox" value="1" name="group[6713][1]" id="mce-group[6713]-6713-0"><label for="mce-group[6713]-6713-0">I would pay $10 for a DRM-free e-book with tons of Physics in JS.</label>
</div>
<div id="mce-responses" class="clear">
<div class="response" id="mce-error-response" style="display:none"></div>
<div class="response" id="mce-success-response" style="display:none"></div>
</div>	<div class="clear"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
</form>
</div>
<!--End mc_embed_signup--><!--kg-card-end: markdown--><!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Modeling Physics in Javascript: Gravity and Drag]]></title><description><![CDATA[<!--kg-card-begin: markdown--><!--kg-card-begin: markdown--><p>This is the first post in the <a title="Modeling Physics in Javascript: Introduction" href="http://burakkanber.com/blog/modeling-physics-in-javascript-introduction/">Modeling Physics in Javascript</a> 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 &quot;that's not the whole story&quot; at me when</p>]]></description><link>https://burakkanber.com/blog/modeling-physics-javascript-gravity-and-drag/</link><guid isPermaLink="false">59b43b8b934a21000178fc21</guid><category><![CDATA[Physics]]></category><dc:creator><![CDATA[Burak Kanber]]></dc:creator><pubDate>Thu, 06 Sep 2012 16:00:00 GMT</pubDate><content:encoded><![CDATA[<!--kg-card-begin: markdown--><!--kg-card-begin: markdown--><p>This is the first post in the <a title="Modeling Physics in Javascript: Introduction" href="http://burakkanber.com/blog/modeling-physics-in-javascript-introduction/">Modeling Physics in Javascript</a> 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 &quot;that's not the whole story&quot; 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.</p>
<!-- more -->
<blockquote>
<p><em>Yes, there's a JSFiddle to play with at the bottom of the page!</em></p>
</blockquote>
<h2>The Problem</h2>
Model a bouncy ball, under the influence of gravity, which can bounce off of horizontal or vertical walls. Oh, and it experiences air drag.
<p>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.</p>
<h2>Newton's 2nd Law</h2>
Newton's 2nd Law of Motion basically <em>is</em> physics. It describes how forces interact with macroscopic objects. If you've ever seen a ball fly through the air, or a car moving, or something rolling down a hill, or if you've ever <em>felt</em> anything, you know (indirectly) about Newton's 2nd Law.
<p>Newton's 2nd Law looks like this: F = ma.</p>
<p>Well, not quite. It looks more like this: <strong>F<sub>net</sub></strong> = m<strong>a</strong>.</p>
<p>As you can imagine, physics has a manner of starting simple and then getting very complicated very quickly. The subscript &quot;net&quot; means that the &quot;F&quot; doesn't just refer to a single force, but the sum total of all forces on the object. The bold &quot;F&quot; and &quot;a&quot; mean that those variables (force and acceleration) are vectors -- meaning that they exist separately in 3 different directions (X, Y, and Z).</p>
<p>But that's not too bad. If you don't want to do vector math, you can simply rewrite <strong>F<sub>net</sub></strong> = m<strong>a</strong> as the following three separate equations:</p>
<ul>
	<li>F<sub>x, net</sub> = ma<sub>x</sub></li>
	<li>F<sub>y, net</sub> = ma<sub>y</sub></li>
	<li>F<sub>z, net</sub> = ma<sub>z</sub></li>
</ul>
You may think that having three equations to worry about makes things tougher, but trust me, it doesn't. Just remember that you have to do the F = ma equation for each direction. We'll very rarely use the Z direction, so all we really have to worry about stuff happening in the X and Y directions (left/right, and up/down).
<p>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:</p>
<ul>
	<li>2 Newtons pulling right</li>
	<li>4 N pulling left</li>
	<li>1 N pulling down</li>
</ul>
We combine the left and right forces to get our overall F<sub>x, net</sub> = -2 N. (4 to the left and 2 to the right leaves us with 2 left over pulling to the left. The number is negative because in general, we'll consider "right" to be positive and "left" to be negative.)
<p>And since there's only one force acting in the Y direction, the F<sub>y, net</sub> is just -1 N. (Let's say &quot;up&quot; is positive and &quot;down&quot; is negative -- but <strong>only for now</strong>. We'll switch that up later. In general, you use positive and negative signs in a way that makes sense for your specific problem.)</p>
<p>Finally, since our ball weighs 2 kg, we can substitute our numbers into F = ma and get the following two equations:</p>
<ul>
	<li>-2 N = 2 kg * a<sub>x</sub></li>
	<li>-1 N = 2 kg * a<sub>y</sub></li>
</ul>
So far, so good. Truth be told, we're really interested in the accelerations here, so we'll just rearrange:
<ul>
	<li>a<sub>x</sub> = -2 N / 2 kg</li>
	<li>a<sub>y</sub> = -1 N / 2 kg</li>
</ul>
And then I'll tell you that when you divide "Newtons" by "kilograms" you get "meters per second-squared":
<ul>
	<li>a<sub>x</sub> = -1 m / s<sup>2</sup></li>
	<li>a<sub>y</sub> = -0.5 m / s<sup>2</sup></li>
</ul>
<p>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 &quot;left&quot; and &quot;down&quot;, 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.</p>
<p>(More advanced: sometimes you don't know the X and Y components of a force. It's possible that you only know about <em>one</em> 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.)</p>
<h2>Gravity</h2>
Gravity is one of the universal fundamental interactions, along with the electromagnetic, strong, and weak forces. Gravity causes a force to act on every single object from every other single object, but fortunately everything works out to simplify nicely if you're on the surface of a planet. On Earth, for instance, we don't even need to worry about the <em>force </em>that gravity causes, we can just look at the end result: every single object on Earth experiences an additional downward acceleration of 9.8 m / s<sup>2</sup>. That simple. 
<p>If our ball from above (that we already solved for) is on Earth and experiencing gravity, then we just need to modify the a<sub>y</sub> equation slightly. We'll take the downward acceleration that the force is causing and combine it with the downward acceleration that gravity causes:</p>
<p>a<sub>y</sub> = -0.5 m / s<sup>2</sup> - 9.8 m / s<sup>2</sup></p>
<p>That leaves us with an acceleration of</p>
<p>a<sub>y</sub> = -10.3 m / s<sup>2</sup></p>
<p>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.</p>
<p>So, gravity is simple (if you're on a planet). All you do is modify the a<sub>y</sub> acceleration to factor in the downward pull of gravity.</p>
<p>In a future article we'll look at how to model gravity if you're <em>not</em> on a planet (perhaps you <em>are</em> a planet), but that doesn't come until later...</p>
<h2>Aerodynamic Drag</h2>
<p>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, <em>is</em> a force, and we'll have to model it.</p>
<p>The equation (one of the equations) for aerodynamic drag looks like this:</p>
<p><strong>F<sub>D</sub></strong> = -0.5 * C<sub>D</sub> * A * ρ * <strong>v<sup>2</sup></strong></p>
<p>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:</p>
<ul>
<li>F<sub>D, x</sub> = -0.5 * C<sub>D</sub> * A * &#961; * v<sub>x</sub><sup>2</sup></li>
<li>F<sub>D, y</sub> = -0.5 * C<sub>D</sub> * A * &#961; * v<sub>y</sub><sup>2</sup></li>
</ul>
<p>And then we look at each one of those terms above:</p>
<ul>
<li>C<sub>D</sub> 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.</li>
<li>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 &#960; r<sup>2</sup>.</li>
<li>&#961; (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<sup>3</sup>)</li>
<li>Velocity squared -- since we're looking at this in two directions separately, we use the X velocity and the Y velocity respectively.</li>
<li>Note the -0.5 at the beginning. The negative sign, with the fact that the equation uses velocity, indicates that this force pushes <em>in the opposite direction the ball is moving</em> 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.</li>
</ul>
<h2>A Touch of Calculus</h2>
<p>Calculus, like physics, is amazing and has a wonderful depth that I can't do justice in a blog post.</p>
<p>The &quot;derivative&quot; in calculus describes how something changes as something else is changing; often this will be called the &quot;rate of change&quot;. 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 &quot;derivative of position with respect to time&quot; or simply the &quot;time derivative of position&quot;.</p>
<p>Then we can think about what happens when you speed up or slow down (accelerate). You might change your <em>velocity</em> 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.</p>
<p>So it starts with position. The derivative of position is velocity. And the derivative of velocity is acceleration. (The derivative of acceleration is called &quot;jerk&quot;, and the derivative of jerk is called &quot;jounce&quot;.)</p>
<p>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 <em>where</em> it will be at every moment in the future.</p>
<p>An example: your ball is accelerating at 2 m / s<sup>2</sup> (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;</p>
<table style="width:100%;">
<thead>
<tr>
<th>Time</th>
<th>Accel</th>
<th>Velocity</th>
<th>Position</th>
</tr>
</thead>
<tbody>
<tr>
<td>0 s</td>
<td>2 m / s<sup>2</sup></td>
<td>0 m / s</td>
<td>0 m</td>
</tr>
<tr>
<td>1 s</td>
<td>2 m / s<sup>2</sup></td>
<td>2 m / s</td>
<td>0 m</td>
</tr>
<tr>
<td>2 s</td>
<td>2 m / s<sup>2</sup></td>
<td>4 m / s</td>
<td>2 m</td>
</tr>
<tr>
<td>3 s</td>
<td>2 m / s<sup>2</sup></td>
<td>6 m / s</td>
<td>6 m</td>
</tr>
<tr>
<td>4 s</td>
<td>2 m / s<sup>2</sup></td>
<td>8 m / s</td>
<td>12 m</td>
</tr>
<tr>
<td>5 s</td>
<td>2 m / s<sup>2</sup></td>
<td>10 m / s</td>
<td>20 m</td>
</tr>
<tr>
<td>6 s</td>
<td>2 m / s<sup>2</sup></td>
<td>12 m / s</td>
<td>30 m</td>
</tr>
</tbody>
</table>
<p>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.</p>
<h2>Writing the Code</h2>
<p>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.</p>
<pre><code class="language-javascript">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;
</code></pre>
<p>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 &quot;restitution&quot;. You'll see later that this value determines how bouncy the ball is.</p>
<p>Notice here that we've set the ball to be moving at the start of the simulation.</p>
<p>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.</p>
<p><em>Please play with these values</em> in the JSFiddle below. Change rho and the radius and the mass, and see how physics affects the simulation!</p>
<pre><code class="language-javascript">var setup = function() {
	canvas = document.getElementById(&quot;canvas&quot;);
	ctx = canvas.getContext(&quot;2d&quot;);
	
	canvas.onmousemove = getMousePosition;
	canvas.onmousedown = mouseDown;
	canvas.onmouseup = mouseUp;
	
	ctx.fillStyle = 'red';
	ctx.strokeStyle = '#000000';
	loopTimer = setInterval(loop, frameDelay);
}
</code></pre>
<p>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.</p>
<p>In the loop:</p>
<pre><code class="language-javascript">// 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;
</code></pre>
<p>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 &quot;if&quot; statements to see if the velocity is positive or negative, I just do:</p>
<pre><code class="language-javascript">ball.velocity.y / Math.abs(ball.velocity.y)
</code></pre>
<p>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.</p>
<p>After that, we calculate acceleration. Notice that the statement for &quot;ay&quot; is different from &quot;ax&quot;. Gravity only works in the Y direction, so we add that in here. Also notice that in this problem, &quot;downwards&quot; is positive, unlike the example at the top of the page.</p>
<p>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 &quot;meters per <em>second</em>-squared&quot;. 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.</p>
<p>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 &quot;1px = 1cm&quot;, so this *100 is just an adjustment to make everything work out in meters.</p>
<p>Then we handle collisions with the walls:</p>
<pre><code class="language-javascript">// Handle collisions
if (ball.position.y &gt; height - ball.radius) {
	ball.velocity.y *= ball.restitution;
	ball.position.y = height - ball.radius;
}
if (ball.position.x &gt; width - ball.radius) {
	ball.velocity.x *= ball.restitution;
	ball.position.x = width - ball.radius;
}
if (ball.position.x &lt; ball.radius) {
	ball.velocity.x *= ball.restitution;
	ball.position.x = ball.radius;
}
</code></pre>
<p>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!</p>
<p>We also modify the position of the ball to just kiss the wall -- this way the ball won't get stuck &quot;in&quot; 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.</p>
<p>Finally, since we want to be able to control the ball with the mouse, we'll add some handlers (not all code shown here):</p>
<pre><code class="language-javascript">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;
	}
}
</code></pre>
<p>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 &quot;initial velocity&quot; technique above just lets you un-naturally override the velocity in an instant and let physics figure everything out again.</p>
<p>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.</p>
<p>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.</p>
<iframe style="width: 100%; height: 500px; border:1px solid #CCC;" src="https://jsfiddle.net/bkanber/39jrM/embedded/" allowfullscreen="allowfullscreen" frameborder="0"></iframe>
<!-- Begin MailChimp Signup Form -->
<link href="http://cdn-images.mailchimp.com/embedcode/classic-081711.css" rel="stylesheet" type="text/css">
<style type="text/css">
	#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
	#mc_embed_signup form { padding: 0 }
</style>
<div id="mc_embed_signup">
<form action="http://burakkanber.us5.list-manage.com/subscribe/post?u=3269dc566d381f05852d92aa8&amp;id=73795f99d0" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate="">
	<h2>Email me when new Physics in JS articles are written</h2>
<div class="mc-field-group">
	<label for="mce-EMAIL">Email Address </label><input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL">
</div>
<div class="mc-field-group input-group">
    <strong>Survey: would you buy a Physics in JS e-book? </strong>
    <input type="checkbox" value="1" name="group[6713][1]" id="mce-group[6713]-6713-0"><label for="mce-group[6713]-6713-0">I would pay $10 for a DRM-free e-book with tons of Physics in JS.</label>
</div>
<div id="mce-responses" class="clear">
<div class="response" id="mce-error-response" style="display:none"></div>
<div class="response" id="mce-success-response" style="display:none"></div>
</div>	<div class="clear"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
</form>
</div>
<!--End mc_embed_signup--><!--kg-card-end: markdown--><!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Modeling Physics in Javascript: Introduction]]></title><description><![CDATA[<!--kg-card-begin: markdown--><!--kg-card-begin: markdown--><p>Physics in Javascript Table of Contents:</p>
<ul>
	<li><a title="Modeling Physics in Javascript: Gravity and Drag" href="http://burakkanber.com/blog/modeling-physics-javascript-gravity-and-drag/" target="_blank">Gravity and Drag</a></li>
	<li><a title="Physics in Javascript: Car Suspension – Part 1 (Spring, Mass, Damper)" href="http://burakkanber.com/blog/physics-in-javascript-car-suspension-part-1-spring-mass-damper/" target="_blank">Spring-Mass-Damper (Car Suspension, Part 1)</a></li>
	<li><a href="http://burakkanber.com/blog/physics-in-javascript-rigid-bodies-part-1-pendulum-clock/" title="Physics in Javascript: Rigid Bodies — Part 1 (Pendulum Clock)" target="_blank">Rigid Bodies, Part 1 (Pendulum Clock)</a></li>
</ul>
<!-- more -->
<p>Another post that starts with &quot;I love&quot;:</p>
<p>I love physics. I really do. Once upon a time I was a real engineer (Master in Mechanical Engineering, hybrid car</p>]]></description><link>https://burakkanber.com/blog/modeling-physics-in-javascript-introduction/</link><guid isPermaLink="false">59b43b8b934a21000178fc22</guid><category><![CDATA[Physics]]></category><dc:creator><![CDATA[Burak Kanber]]></dc:creator><pubDate>Wed, 05 Sep 2012 16:00:00 GMT</pubDate><content:encoded><![CDATA[<!--kg-card-begin: markdown--><!--kg-card-begin: markdown--><p>Physics in Javascript Table of Contents:</p>
<ul>
	<li><a title="Modeling Physics in Javascript: Gravity and Drag" href="http://burakkanber.com/blog/modeling-physics-javascript-gravity-and-drag/" target="_blank">Gravity and Drag</a></li>
	<li><a title="Physics in Javascript: Car Suspension – Part 1 (Spring, Mass, Damper)" href="http://burakkanber.com/blog/physics-in-javascript-car-suspension-part-1-spring-mass-damper/" target="_blank">Spring-Mass-Damper (Car Suspension, Part 1)</a></li>
	<li><a href="http://burakkanber.com/blog/physics-in-javascript-rigid-bodies-part-1-pendulum-clock/" title="Physics in Javascript: Rigid Bodies — Part 1 (Pendulum Clock)" target="_blank">Rigid Bodies, Part 1 (Pendulum Clock)</a></li>
</ul>
<!-- more -->
<p>Another post that starts with &quot;I love&quot;:</p>
<p>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.</p>
<p>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.</p>
<p>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.</p>
<p>And, if you can combine your rudimentary knowledge of physics with your rudimentary knowledge of Javascript, you can build <strong>really cool physics models and simulations.</strong></p>
<p>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.</p>
<p>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.</p>
<p>Buckle up. Here's an example of a grandfather clock that actually simulates <em>real physics </em>for the swinging pendulum -- just to whet your appetite:</p>
<p>(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!)</p>
<iframe style="width: 100%; height: 700px; border: 1px solid #CCC;" src="http://jsfiddle.net/bkanber/uvYw5/embedded/result,js,html,css/" frameborder="0" width="320" height="240"></iframe><!--kg-card-end: markdown--><!--kg-card-end: markdown-->]]></content:encoded></item></channel></rss>