HTML and CSS Reference
In-Depth Information
For the new example, we remove the line in bold and create a new variable at the top of the script:
var radius = 20;
This makes all the balls the same size and mass.
Next, locate the checkCollision function and find this section:
//rotate ball0's velocity
vel0 = rotate(ball0.vx, ball0.vy, sin, cos, true),
//rotate ball1's velocity
vel1 = rotate(ball1.vx, ball1.vy, sin, cos, true),
//collision reaction
vxTotal = vel0.x - vel1.x;
vel0.x = ((ball0.mass - ball1.mass) * vel0.x + 2 * ball1.mass * vel1.x) /
(ball0.mass + ball1.mass);
vel1.x = vxTotal + vel0.x;
This is the part that finds the velocities along the line of collision, and, along with their masses, figures out
the result of the collision. The part labeled “collision reaction” is the code that factors in the conservation of
momentum, and this is the section you can get rid of. You can replace that portion with code that simply
swaps vel0 and vel1 . This makes the whole section shown look like this:
//rotate ball0's velocity
vel0 = rotate(ball0.vx, ball0.vy, sin, cos, true),
//rotate ball1's velocity
vel1 = rotate(ball1.vx, ball1.vy, sin, cos, true);
//collision reaction, swap the two velocities
var temp = vel0;
vel0 = vel1;
vel1 = temp;
Here you eliminate a good bit of math, and if you test the file before and after, you should see the same
thing.
Integrating sound
Something that has been conspicuously absent from this topic has been the use of sound. Although sound
is not directly a part of animation, well-done sound effects can go a long way to making an animation more
immersive and realistic.
One of the most anticipated features of HTML5 is its support for the audio element, enabling native sound
playback in the browser. The good news is that most browsers supporting HTML5 have some kind of
support for audio. The bad news is, at least at the time of writing, the level of implementation varies across
browsers. Because of licensing issues with audio formats, it is often unclear what browser plays which file
type. Although this can be a frustrating environment to develop for, it is not an insurmountable one, if you
 
Search WWH ::




Custom Search