Expect this Unit to take just under 1 hour. To demonstrate what you should have at the end of this Unit, check out the Demo for Unit 3. Don't forget to use the Chrome DevTools to look at the console and check out the source code for how I'm testing the engine.
We're going to create an object called Engine, which will have the functionality of managing a game loop as well as providing a namespace for sub-systems.
Updating our game every frame is something that isn't well handled consistently across all browsers. We'll be using what's called a polyfill - a piece of code that provides the technology that we'd normally expect the browser to provide natively - to help manage that. This requestAniamtionFrame() polyfill lets the browser control our update frequency, which is optimized for performance and synchronized to it's repaint cycle, instead of us setting our own update interval using timers.
I typically put this in a separate file and put any other polyfill or utility code-snippets, which would get included before engine_core.js. For now it's fine just to have it in this file.
This function takes in a function as a parameter which will be called each time the browser fullfills a requestAnimationFrame() request.
Creating the engine definition
Part 1: Adding the file to our project
- Create a subdirectory called js_engine
- Create engine_core.js and put it in this subdirectory.
- Add engine_core.js to our list of engine files to load through modernizr.
Part 2: Writing the engine core
- Add the requestAnimationFrame() polyfill code
- Create the Engine object
- Write a function that returns an object, and assign it to a global variable called "Engine".
- Inside this function, write the three functions we discussed: setGameLoop, pauseGame, unpauseGame.
- Write the constructor function as we discussed.
- Assign this constructor function the three functions through the prototype property.
Part 3: Create an instance of your engine and demonstrate it works
- In main.js, once the engine files have finished loading, create a new instance of the engine.
- Assign the instance a game loop function that prints to the console each frame