Slassh

HTML5 Game Walkthrough 1 - game.js part 1

Feb 26th, 2013
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var FPS = 30; // frames per second. Note that "var" initializes a variable, i.e. a value held by a name
  2. var canvas = null; // canvas and context objects currently set to null, will be defined in init() function
  3. var context2D = null;
  4.  
  5. // when window loads, run the init() function
  6. window.onload = init;
  7.  
  8. function init() {
  9.     canvas = document.getElementById('canvas'); // the canvas object is the HTML element from the web page
  10.     context2D = canvas.getContext('2d'); // the context object is what takes the canvas element from the web page and uses the canvas API to manipulate the pixels (acts as the "screen" for the game)
  11.    
  12.     setInterval(runGame, 1000/FPS); // sets a timer to call the runGame() function every 33.3 miliseconds (this allows it to run at the frame rate set at the top). This is what starts the cycle of the game loop.
  13. }
  14.  
  15. function runGame() {
  16.     // Every frame the game is running, it will call these three functions, one after the other
  17.     // So every operation carried out in these functions will be happening at an incredible rate
  18.     // This is what makes a game run
  19.     handleInput();
  20.     update();
  21.     render();
  22. }
  23.  
  24. function handleInput() {
  25.     // here is where user input will be checked
  26.     // variables will be updated to allow the update() function to make it's logic calculations
  27.     // good practice is to not update the world in this function, only variables that allow the following functions to update the world accordingly.
  28. }
  29.  
  30. function update() {
  31.     // This is where all the logic of the game happens. Velocity, gravity, collision, etc.
  32.     // Usually you wouldn't want this function fully clogged with operations, you would instead make calls to more specific functions that do stuff. But for the purpose of this tutorial, we won't be focusing too much on that.
  33. }
  34.  
  35. function render() {
  36.     // This is where the world will be drawn.
  37.     // The steps of the game loop before this have made all the necessary updates to the variables and objects, allowing us to use those values to draw the objects.
  38. }
Advertisement
Add Comment
Please, Sign In to add comment