HTML and CSS Reference
In-Depth Information
And finally, you're going to integrate the function within your update loop, as shown in Listing 8-27.
Listing 8-27. Integrating the paintBall() Function in the Update Loop
function update(ts) {
// Calculate the delta between the previous timestamp and the new one
delta = ts - previousTs;
// Performing a calculation here means that it will be
// executed every 16.67 ms. at 60 frames per second
// Check whether or not something needs to be repainted in the scene
// Only execute the paint routine if the delta is bigger
// than the interval and the shouldRepaint flag is set to true
if (delta > interval && shouldRepaint) {
// This bit will be executed only if it's bigger than the
// interval and therefore will be executed every 33.33 ms.
// at 30 frames per second (or the value of the "fps" variable)
// There's no need to go through all this logic on every frame
shouldRepaint = false;
console.time("Painting Scene");
// Paint the image on the canvas
ctx.drawImage(backgroundTexture,
0,
0);
// If the position of the ball in the X axis minus its radius
// multipled by 2 is less than 0, or it's bigger than the width
// of the canvas, invert the velocity
if (ballPositionX - (ballRadius * 2) < 0 ||
ballPositionX + (ballRadius * 2) > canvas.width) {
ballVelocityX *= -1;
}
// If the position of the ball in the Y axis minus its radius
// multipled by 2 is less than 0, or it's bigger than the width
// of the canvas, invert the velocity
if (ballPositionY - (ballRadius * 2) < 0 ||
ballPositionY + (ballRadius * 2) > canvas.height) {
ballVelocityY *= -1;
}
 
Search WWH ::




Custom Search