HTML and CSS Reference
In-Depth Information
case 87: // W
console.log('Go up!');
break;
case 83: // S
console.log('Go down!');
break;
}
}
Listing 8-8 shows how to display and control the small red circle using your keyboard.
Listing 8-8. Display and Controlling the Small Red Dot
;(function() {
var fps = 30, // Define the maximum number of FPS
interval = 1000 / fps, // Calculate the interval in milliseconds
delta = 0, // Variable initialisation
previousTs = 0,// Variable initialisation
shouldRepaint = true, // Set the repaint flag to true by default
Grid = [], // Initialize an array where we're going to be storing the grid values
gridCols = 15, // Setup the number of columns of the grid
gridRows = 10, // Setup the number of rows of the grid
viewportWidth = 640, // Setup the width of the viewport (the canvas)
viewportHeight = 480, // Setup the height of the viewport (the canvas)
cellWidth = (viewportWidth / gridCols) >> 0, // The width of each cell is calculated
dynamically with the width of the canvas. Floor the result.
cellHeight = (viewportHeight / gridRows) >> 0, // The height of each cell is calculated
dynamically with the height of the canvas. Floor the result.
playerRadius = 10, // Our player is going to be a circle. Set the radius.
playerPositionX = (cellWidth * gridCols) - playerRadius, // Position the player within the map
playerPositionY = (cellHeight * gridRows) - playerRadius, // Position the player within the map
playerVelocityX = 0, // Velocity of the player's movements in the X axis
playerVelocityY = 0, // Velocity of the player's movements in the Y axis
playerVelocityLimit = 2, // Limit the acceleration
canvas = document.querySelector('canvas'), // Grab a reference to the canvas object...
ctx = canvas.getContext('2d'), // ...and its context
i = 0, // Declare counters for the for loop we'll be using below
j = 0; // Declare counters for the for loop we'll be using below
// Set the size of the canvas
canvas.width = viewportWidth;
canvas.height = viewportHeight;
// Initialise the grid. By default, it will be empty,
// so we'll need to "paint" all the cells
for ( ; i < gridRows ; ++i ) {
for ( j = 0 ; j < gridCols ; ++j ) {
if (Grid[i] === undefined) {
Grid[i] = [];
}
 
Search WWH ::




Custom Search