HTML and CSS Reference
In-Depth Information
Figure 8-3. Chained springs
Springing to multiple targets
Back when the subjects of velocity and acceleration were introduced in Chapter 5, we saw how you could
have multiple forces acting on an object. Each type of force is represented as a value, which we add to a
cumulative velocity value, that is then applied to the motion of the object. Since a spring is nothing more
than something exerting acceleration on an object, it's pretty simple to create multiple springs acting on a
single object.
To demonstrate springing to multiple targets, we'll create three “handles”—which will be instances of the
Ball class—and give them simple drag-and-drop functionality. These will also act as targets for the ball to
spring to. The ball will try to spring to all three of them at once and find its equilibrium somewhere between
them. Or, to put it another way, each target will exert a certain amount of acceleration on the ball, and its
motion will be the sum total of all of those forces.
This example gets pretty complex, with several methods in place to handle the various behaviors. First,
here's the complete example (document 12-multi-spring.html ), then we'll discuss it section by section.
Figure 8-4 shows an example of the results of this code.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Multi Spring</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<script src="utils.js"></script>
<script src="ball.js"></script>
<script>
window.onload = function () {
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
mouse = utils.captureMouse(canvas),
ball = new Ball(20),
 
Search WWH ::




Custom Search