HTML and CSS Reference
In-Depth Information
Collision detection and reaction
For your particles, there needs to be some kind of collision detection and reaction. What you do is up to
you. You can have them explode and disappear, or have one particle disappear and add its mass to the
other one, as if they had joined. In the next example, we'll just have them bounce off each other.
We can use some nice collision and reaction code left over from the previous chapter, in a function called
checkCollision . Let's plug that into the move function, like so:
function move (partA, i) {
partA.x += partA.vx;
partA.y += partA.vy;
for (var partB, j = i + 1; j < numParticles; j++) {
partB = particles[j];
checkCollision(partA, partB);
gravitate(partA, partB);
}
}
Only that one line in bold has changed. And of course, you must copy and paste the checkCollision and
rotate functions into the file. This code can be found in document 02-gravity-bounce.html .
Now the particles are attracted to each other, but bounce off when they hit. Change the mass of the
particles and see how they attract differently. You can even do bizarre things such as give the particles
negative mass and watch them repel each other!
In the document 03-gravity-random.html , we kept everything the same except for a few lines at the top
of the script where the particles are initialized:
for ( var size , particle, i = 0; i < numParticles; i++) {
size = Math.random() * 20 + 5;
particle = new Ball( size );
particle.x = Math.random() * canvas.width;
particle.y = Math.random() * canvas.height;
particle.mass = size;
particles.push(particle);
}
This gives each particle a random size and a mass based on that size, as you can see in Figure 12-2.
Things are now starting to get interesting.
 
Search WWH ::




Custom Search