HTML and CSS Reference
In-Depth Information
<canvas id="canvas" width="400" height="400"></canvas>
<script src="utils.js"></script>
<script src="ball.js"></script>
<script>
window.onload = function () {
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
ball0 = new Ball(),
ball1 = new Ball();
ball0.mass = 2;
ball0.x = 50;
ball0.y = canvas.height / 2;
ball0.vx = 1;
ball1.mass = 1;
ball1.x = 300;
ball1.y = canvas.height / 2;
ball1.vx = -1;
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
ball0.x += ball0.vx;
ball1.x += ball1.vx;
var dist = ball1.x - ball0.x;
if (Math.abs(dist) < ball0.radius + ball1.radius) {
//reaction will go here
}
ball0.draw(context);
ball1.draw(context);
}());
};
</script>
</body>
</html>
With this basic setup in place, we'll now look at how to program the reaction. Taking ball0 first, and
considering that ball0 is object 0 and ball1 is object 1, you need to apply the following formula:
(m0 - m1) × v0 + 2 × m1 × v1
v0Final = ----------------------------
m0 + m1
In JavaScript, this becomes the following code:
var vx0Final = ((ball0.mass - ball1.mass) * ball0.vx + 2 * ball1.mass * ball1.vx) /
(ball0.mass + ball1.mass);
It shouldn't be too hard to see where that came from. You can then do the same thing with ball1 , so this:
Search WWH ::




Custom Search