HTML and CSS Reference
In-Depth Information
springAmount = 0.001;
In the spring examples in Chapter 8, you used something like 0.03 for a spring amount. You need to use
something even lower here, because a lot more particles are interacting. If the value is too high, the
velocity will build up too fast. But, if the value is too low, the particles will just stroll across the screen,
seemingly unaware of each other. After we declare the particles, we initialize them:
for (var particle, i = 0; i < numParticles; i++) {
particle = new Ball(5, "#ffffff");
particle.x = Math.random() * canvas.width;
particle.y = Math.random() * canvas.height;
particle.vx = Math.random() * 6 - 3;
particle.vy = Math.random() * 6 - 3;
particles.push(particle);
}
This creates several particles, throws them around the canvas, and gives them random velocities. There's
no mass on these particles, but in a later section, we show you an experiment that adds mass back.
Next comes the drawFrame animation loop, which iterates over the particles twice per frame. Each particle
is passed to the move and draw functions:
function move (partA, i) {
partA.x += partA.vx;
partA.y += partA.vy;
if (partA.x > canvas.width) {
partA.x = 0;
} else if (partA.x < 0) {
partA.x = canvas.width;
}
if (partA.y > canvas.height) {
partA.y = 0;
} else if (partA.y < 0) {
partA.y = canvas.height;
}
for (var partB, j = i + 1; j < numParticles; j++) {
partB = particles[j];
spring(partA, partB);
}
}
This is similar to the previous examples where we added in screen wrapping. But instead of calling
gravitate , we use the spring function :
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) {
var ax = dx * springAmount,
ay = dy * springAmount;
Search WWH ::




Custom Search