HTML and CSS Reference
In-Depth Information
satellite guidance system for NASA, you might want to leave
G
in there. But if you're programming the next
great space wars game, you can probably live without it.
Now that you have the updated formula, let's put it into code. In the
drawFrame
animation loop, iterate
over each particle and pass it to the
move
function. Inside that you call another function named
gravitate
so you can separate the code that handles gravity:
function move (partA, i) {
partA.x += partA.vx;
partA.y += partA.vy;
for (var partB, j = i + 1; j < numParticles; j++) {
partB = particles[j];
gravitate(partA, partB);
}
}
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
particles.forEach(move);
particles.forEach(draw);
}());
In the
move
function, you use a
for
loop to get the interactions of one particle to the rest. After you have
partA
and
partB
, you pass these two objects to the
gravitate
function, which is:
function gravitate (partA, partB) {
var dx = partB.x - partA.x,
dy = partB.y - partA.y,
distSQ = dx * dx + dy * dy,
dist = Math.sqrt(distSQ),
force = partA.mass * partB.mass / distSQ,
ax = force * dx / dist,
ay = force * dy / dist;
partA.vx += ax / partA.mass;
partA.vy += ay / partA.mass;
partB.vx -= ax / partB.mass;
partB.vy -= ay / partB.mass;
}
In this function, you first find the distance (
dx
and
dy
) between the two particles, and the total distance.
Remember that the formula for gravity,
force = m
1
×
m
2
/ distance
2
, contains the distance squared.
Normally, we calculate distance all at once using:
dist = Math.sqrt(dx * dx + dy * dy)
. But then to
get distance squared, we would square something that was a square root—that's double work. If we use
the variable
distSQ
to grab a reference to
dx * dx + dy * dy
before we take the square root, we save
ourselves that calculation.
Next, we find the total force by multiplying the masses and dividing by the distance squared. Then we
figure the total acceleration on the x and y axes. Again, we use the shortcut we discussed at the end of