HTML and CSS Reference
In-Depth Information
That's the general strategy, but to use the terms discussed in this chapter: object A has object B as its
target. It springs toward it. Object B in turn has object A as its target, and this is where the offset is
important. If each object had the other as a direct target, they would collapse in on each other and occupy
the same point. By applying an offset, you keep them apart a bit, as shown in Figure 8-6.
Figure 8-6.
Two objects connected
For this next example, you'll create two instances of the
Ball
connected by a spring, and we'll call them
ball0
and
ball1
.
ball0
springs to
ball1
with an offset, and
ball1
springs to
ball0
with an offset.
Rather than writing out all the offset, spring, and motion code twice, it's all put into a function named
springTo
. You can spring
ball0
to
ball1
by calling
springTo(ball0, ball1)
, and then spring
ball1
to
ball0
by calling
springTo(ball1, ball0)
. There are also a couple of variables that have been
added:
ball0
_
dragging
and
ball1
_
dragging
, to disable the springing for each ball when it is being
dragged. Here's the document (
14-double-spring.html
):
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Double 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),
ball0 = new Ball(20),
ball1 = new Ball(20),
ball0
_
dragging = false,
ball1
_
dragging = false,
spring = 0.03,
friction = 0.9,
springLength = 100,
vx = 0,
vy = 0;
ball0.x = Math.random() * canvas.width;
ball0.y = Math.random() * canvas.height;
ball1.x = Math.random() * canvas.width;
ball1.y = Math.random() * canvas.height;