HTML and CSS Reference
In-Depth Information
Springing
Springing is one of the most powerful and useful physics concepts in programmed animation. It seems like
you can do almost anything with a spring, but of course, it's just another technique. Since you can do so
much with a spring, let's take a look at what it is and how you can program it.
As mentioned at the beginning of the chapter, the acceleration of a spring is proportional to its distance
from a target. Think about a real, physical spring, or better yet, a ball on the end of a rubber band. You
attach the other end to something solid. As the ball is hanging there with no force applied, that's its target
point. That's where it wants to be. Now pull it away a tiny bit and let it go. At that point, the ball's velocity is
zero, but the rubber band applies force to it, pulling it back to the target. Now pull it away as far as you can
and let it go. The rubber band applies a lot more force. The ball zooms right past its target and starts going
the other way. Its velocity is very high. But when it gets a little bit past the target, the rubber band starts
pulling it back a bit—changes its velocity. The ball keeps going, but the farther it goes, the more the band
pulls back on it. Eventually, the velocity reaches zero, the direction reverses, and the whole thing starts
over again. Finally, after bouncing back and forth a few times, it slows down and comes to a stop at—you
guessed where—its target.
Now, let's start translating this into code so you can use it. To keep things simple, let's start off with one
dimension.
Springing in one dimension
Once again, we'll use the red ball to demonstrate this idea. You'll leave it over at its default x position of
zero and have it spring to the middle of the canvas. As with easing, you'll need a variable to hold the
proportionate value of the spring. You can think of this as the proportion of the distance that will be added
to the velocity. A high spring value will make a very stiff spring. Something lower will look more like a loose
rubber band. You'll start off with 0.1, and here's the initial code:
var spring = 0.1,
targetX = canvas.width / 2,
vx = 0;
Again, don't worry about where to put this just yet. Just make sure you know what these variables and
statements are doing.
Then we begin the motion code and find the distance to the target:
var dx = targetX - ball.x;
Now, compute some acceleration. The acceleration will be proportional to that distance, in fact, it will be
the distance multiplied by the spring value:
var ax = dx * spring;
Once you have a value for acceleration, you should be back on familiar ground. Add the acceleration to
the velocity and add the velocity to the position:
vx += ax;
ball.x += vx;
 
Search WWH ::




Custom Search