Creating a Scrolling Tile Map
To build a nethack-style game, the engine needs to add a 2-D tile map to the game in an efficient manner. One naive way to do this would be to just add an absolutely positioned sprite at each position. This does work; however, as the map gets larger, it slows the browser down to a crawl. Instead, you want to create a single large sprite that can be moved around as a unit and treated like a single element.
Understanding the Performance Problem
If you take a medium-sized map that might be 50 tiles tall by 50 tiles wide, this would result in 2,500 sprites, each of which needs to be stepped every frame. In addition, every time you make a modification to an element, the browser needs to repaint the container, resulting in a significant slowdown in frame rate from constantly updating. If you don’t create a more efficient mechanism of collision detection than looping over every potential object, then every moving sprite would need to be tested in each iteration. All this would lead to exceedingly small map sizes or horrible performance.
A better plan of attack would be to create a single tile map sprite that contains all the tiles and that can be stepped and moved around as a single entity. Because the individual tiles aren’t moving, collision detection is as simple as dividing a position by the size of each tile to get a tile position and checking that one location.
Implementing the DOM Tile Map Class
For all these reasons the engine adds in a class called ...
Get Professional HTML5 Mobile Game Development now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.