HTML and CSS Reference
In-Depth Information
partA.vx += ax;
partA.vy += ay;
partB.vx -= ax;
partB.vy -= ay;
}
}
Here, you find the distance between the two particles. If it's
not less
than
minDist
, you move on. But if it is
less
, you determine the acceleration on each axis, based on the distance and
springAmount
. You add
that acceleration to
partA
's velocity and subtract it from
partB
's velocity. This pulls the particles together.
Try it out and you see something like Figure 12-4. The particles clump together like flies buzzing around a
garbage can. But even those clumps move around, break up, and join other clumps. It's interesting
emergent behavior. Change the
minDist
and
springAmount
values to see what happens.
Figure 12-4.
Nodes in action
Nodes with connections
Although it is obvious that the nodes are interacting with one other, it's not obvious what the specific
interaction is between each pair of nodes. However, we can visualize this by drawing lines between the
nodes, and that's simple to do—just add some canvas drawing code to the
spring
function. If two nodes
interact, this draws a line between them:
function spring (partA, partB) {
var dx = partB.x - partA.x,
dy = partB.y - partA.y,
dist = Math.sqrt(dx * dx + dy * dy);
if (dist < minDist) {
context.strokeStyle = "#ffffff";
context.beginPath();
context.moveTo(partA.x, partA.y);