HTML and CSS Reference
In-Depth Information
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
particles = [],
numParticles = 2,
sun = new Ball(100, "#ffff00"),
planet = new Ball(10, "#00ff00");
sun.x = canvas.width / 2;
sun.y = canvas.height / 2;
sun.mass = 10000;
particles.push(sun);
planet.x = canvas.width / 2 + 200;
planet.y = canvas.height / 2;
planet.vy = 7;
planet.mass = 1;
particles.push(planet);
Decrease planet.vy a little to see how it falls out of orbit and plummets towards the sun (and bounces
right off).
As an extra bonus, stop clearing the canvas element in the drawFrame function to trace the orbit path with
a line:
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
particles.forEach(move);
particles.forEach(draw);
}());
This example is in 04-orbit-draw.html , and you can make some interesting patterns by playing around
with the variables.
Springs
The other kind of particle attraction you probably want to try is springs. Recall that in Chapter 8, you tried
out chains of springs and objects springing to each other. Here, you look at a broader application, where
you have many particles, all springing to each other, as in the gravity examples you just saw.
The inspiration for this example came from a piece called “Node Garden” by Jared Tarbell
( www.levitated.net ), written for Flash. The idea is that you have several nodes (particles), and they
each have various types of interactions with any other nearby nodes.
Gravity versus springs
If you look at gravity and springs, you see they are similar, yet almost exactly opposite. Both apply
acceleration to two objects to pull them together. But in gravity, the farther apart the objects are, the less
acceleration there is. In a spring, the acceleration gets larger as the distance increases.
 
Search WWH ::




Custom Search