HTML and CSS Reference
In-Depth Information
ball.vx *= bounce;
} else if (ball.x - ball.radius < 0) {
ball.x = ball.radius;
ball.vx *= bounce;
}
if (ball.y + ball.radius > canvas.height) {
ball.y = canvas.height - ball.radius;
ball.vy *= bounce;
} else if (ball.y - ball.radius < 0) {
ball.y = ball.radius;
ball.vy *= bounce;
}
}
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
ball0.x += ball0.vx;
ball0.y += ball0.vy;
ball1.x += ball1.vx;
ball1.y += ball1.vy;
checkCollision(ball0, ball1);
checkWalls(ball0);
checkWalls(ball1);
ball0.draw(context);
ball1.draw(context);
}());
};
</script>
</body>
</html>
In this exercise, you set the boundaries, set some random velocities, throw in some mass, move each ball
according to its velocity, and check the boundaries. You notice that the boundary-checking code has been
moved into its own function, checkWalls , and we still need to write the function for collision-checking.
The beginning of the checkCollision function is simple; it's just a distance-based collision detection
setup:
function checkCollision (ball0, ball1) {
var dx = ball1.x - ball0.x,
dy = ball1.y - ball0.y,
dist = Math.sqrt(dx * dx + dy * dy);
if (dist < ball0.radius + ball1.radius) {
//collision handling code here
}
}
Search WWH ::




Custom Search