ebook img

HTML5 Game Development Insights PDF

457 Pages·2014·15.35 MB·English
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview HTML5 Game Development Insights

BOOKS FOR PROFESSIONALS BY PROFESSIONALS® McAnlis Lubbers et al. HTML5 Game Development Insights RELATED HTML5 Game Development Insights is a from-the-trenches collection of tips, tricks, hacks, and advice straight from professional HTML5 game developers. The 24 chapters here include unique, cutting edge, and essential techniques for creating and optimizing modern HTML5 games. You will learn things such as using the Gamepad API, real-time networking, getting 60fps full screen HTML5 games on mobile, using languages such as Dart and TypeScript, and tips for streamlining and automating your workflow. Game development is a complex topic, but you don’t need to reinvent the wheel. HTML5 Game Development Insights will teach you how the pros do it. The book is comprised of six main sections: Performance; Game Media: Sound and Rendering; Networking, Load Times, and Assets; Mobile Techniques and Advice; Cross-Language JavaScript; Tools and Useful Libraries. Within each of these sections, you will find tips that will help you work faster and more efficiently and achieve better results. Presented as a series of short chapters from various professionals in the HTML5 gaming industry, all of the source code for each article is included and can be used by advanced programmers immediately. What You’ll Learn: • “From The Trenches” tips, hacks, and advice on HTML5 game development • Best practices for building Mobile HTML5 games • Actionable advice and code for both professional and novices Shelve in ISBN 978-1-4302-6697-6 Web Development/JavaScript 54999 User level: Intermediate–Advanced SOURCE CODE ONLINE 9 781430 266976 www.apress.com www.it-ebooks.info For your convenience Apress has placed some of the front matter material after the index. Please use the Bookmarks and Contents at a Glance links to access them. www.it-ebooks.info Contents at a Glance About the Authors ��������������������������������������������������������������������������������������������������������������xix About the Technical Reviewers ���������������������������������������������������������������������������������������xxiii Introduction ����������������������������������������������������������������������������������������������������������������������xxv ■ Chapter 1: JavaScript Is Not the Language You Think It Is �����������������������������������������������1 ■ Chapter 2: Optimal Asset Loading �����������������������������������������������������������������������������������15 ■ Chapter 3: High-Performance JavaScript ������������������������������������������������������������������������43 ■ Chapter 4: Efficient JavaScript Data Structures ��������������������������������������������������������������59 ■ Chapter 5: Faster Canvas Picking �����������������������������������������������������������������������������������69 ■ Chapter 6: Autotiles ���������������������������������������������������������������������������������������������������������87 ■ Chapter 7: Importing Flash Assets ����������������������������������������������������������������������������������99 ■ Chapter 8: Applying Old-School Video Game Techniques in Modern Web Games ���������105 ■ Chapter 9: Optimizing WebGL Usage �����������������������������������������������������������������������������147 ■ Chapter 10: Playing Around with the Gamepad API ������������������������������������������������������163 ■ Chapter 11: Introduction to WebSockets for Game Developers �������������������������������������177 ■ Chapter 12: Real-Time Multiplayer Network Programming ������������������������������������������195 ■ Chapter 13: The State of Responsive Design �����������������������������������������������������������������211 ■ Chapter 14: Making a Multiplatform Game �������������������������������������������������������������������221 ■ Chapter 15: Developing Better Than Native Games �������������������������������������������������������231 ■ Chapter 16: Mobile Web Game Techniques with Canvas 2D API �����������������������������������245 ■ Chapter 17: Faster Map Rendering ��������������������������������������������������������������������������������263 iii www.it-ebooks.info ■ Contents at a GlanCe ■ Chapter 18: HTML5 Games in C++ with Emscripten ������������������������������������������������������283 ■ Chapter 19: Introduction to TypeScript: Building a Rogue-like Engine �������������������������299 ■ Chapter 20: Implementing a Main Loop in Dart �������������������������������������������������������������325 ■ Chapter 21: Saving Bandwidth and Memory with WebGL and Crunch ��������������������������337 ■ Chapter 22: Creating a Two-Dimensional Map Editor ����������������������������������������������������361 ■ Chapter 23: Automating Your Workflow with Node�js and Grunt �����������������������������������383 ■ Chapter 24: Building a Game with the Cocos2d-html5 Library �������������������������������������395 Index ���������������������������������������������������������������������������������������������������������������������������������437 iv www.it-ebooks.info Introduction Making games is hard. Even most veteran game developers don’t fully grasp the scale of how difficult it is to weave together technology, code, design, sound, and distribution to produce something that resonates with players around the world. As industries go, game development is still fairly young, only really gaining traction in the early 1980s. This makes it an even more difficult process, which, frankly, we’re still trying to figure out. In 30 years of game development, we’ve seen the boom of console games, computer games, Internet bubbles, shareware, social gaming, and even mobile gaming. It seems that every five to eight years, the entire industry reinvents itself from the core in order to adjust to the next big thing. As hardware trends shift and user tastes change, modern game developers scramble to keep up, producing three to four games in a single year (a feat unheard of in 2001, when you thought in terms of shipping two to three games in your entire career). This rapid pace comes at a high cost: engineers often have to build entire virtual empires of code, only to scrap them a mere six weeks later to design an entirely different gameplay dynamic. Designers churn through hordes of ideas in a week in order to find the smallest portion of fun that they can extract from any one idea. Artists also construct terabytes of content for gameplay features that never see the light of day. A lot of tribal knowledge and solutions get lost in this frantic process; many techniques, mental models, and data just evaporate into the air. Tapping into the brains of game developers, cataloging their processes, and recording their techniques is the only real way to grow as an industry. This is especially relevant in today’s game development ecosystem, where the number of “indie” developers greatly outnumbers the “professional” developers. Today we’re bombarded with messaging about how “it’s never been easier to make a game,” which is true to some extent. The entry barrier to creating a game is pretty low; eight-year olds can do it. The real message here is what it takes to make a great game. Success comes from iteration; you can’t just point yourself in a direction, move toward it, and expect your game to be great. You have to learn. You have to grow. You have to evolve. Moreover, with less and less time between product shipments, the overhead available to grow as a developer is quickly getting smaller and smaller. Developers can’t do it on their own; they need to learn, ask questions, and see what everyone else is doing. As a developer, you have to find mentors in design, marketing, and distribution. You have to connect with other people who feel your pain, and who are trying to solve the same problems and fight the same battles. Evolve as a community, or die as an individual. Making games is hard. That’s why we wrote this book; even the best of us must find time to learn. —Colt McAnlis HTML5 has come a long way. It might be hard to believe today, but getting publisher support for Pro HTML5 Programming, the book I co-authored with Brian Albers and Frank Salim in 2009, and released as one of the first books on the subject in 2010, was quite hard. Publishers were just not sure if this new HTML5 thing had a future or if it was just a passing fad. The launch of the iPad in April 2010 changed all that overnight and drove the curiosity and excitement about HTML5 to a whole new level. For the first time, many developers started to look seriously at the new features and APIs, such as canvas, audio, and video. The possibility of many kinds of new web applications with real native feature support seemed almost too good to be true. And, to a certain extent, it was. xxv www.it-ebooks.info ■ IntroduCtIon When developers seriously started to dig into the new APIs, they discovered many missing pieces. Features that had long been staples of other platforms were now lacking, or were implemented in such a way that they were not very useful. This disappointed many developers, and yet they were eager to improve on the HTML5 feature set. That cycle is, of course, the nature of development and the impetus for innovation. Game software, perhaps more than any other genre, tends to stress its host platform to the max, so it was not surprising that there was some backlash to the initial hype that HTML5 was the be-and-end-all for every application on the web. However, that was never the intention of HTML5. In fact, one of the core design principles behind HTML5 is “evolution not revolution,” and it is the slow but steady progress of features, spanning many years, that has changed the HTML landscape. Nevertheless, browser vendors and spec authors have not been sitting still. Instead, they have developed many new and more powerful APIs. One example is the Web Audio API, now shipping in many of the major browsers. This API offers fine-grained audio manipulation, which the regular audio element could not provide. With this and other new APIs, it is now much easier to develop applications and web-based games that, until recently, would have been hard to imagine, let alone code. That is why I believe we’re just at the beginning of a future full of great possibilities in web-based game software. Of course, we’ll never be “done.” There will always be room for improvement but, as my esteemed co-authors clarify in this book, you can now build compelling games that leverage the power and flexibility of the web platform in ways that were unheard of even a few years ago. Code, learn, improve, and repeat. Be a part of software evolution at its best. —Peter Lubbers xxvi www.it-ebooks.info Chapter 1 JavaScript Is Not the Language You Think It Is Sean Bennett, Course Architect, Udacity JavaScript is a deceptively familiar language. Its syntax is close enough to C/C++ that you may be tricked into thinking it behaves similarly. However, JavaScrit has a number of gotchas that trip up developers coming from other languages. In this chapter, I’ll go over some of the more egregious offenders, teach you how to avoid them, and showcase the hidden power in the language. This chapter is for game programmers who are coming from other languages and who are using JavaScript for the first time. It’s the tool I wish I’d had when I first started using JavaScript. Variables and Scoping Rules You wouldn’t think that declaring variables would be at all hard or error prone. After all, it’s a fundamental part of any language, right? The problem is that with JavaScript, it’s • very easy to accidentally declare variables after they’re used, which leads to accidentally accessing undefined variables • deceptively difficult to restrict access to variables, leading to naming collisions as well as memory allocation issues I’ll discuss the issues with and limitations of JavaScript scoping and then present a well-known solution for modularizing your JavaScript code. Declaration Scoping The first thing you need to realize about JavaScript is that there are only two different scopes: global and function level. JavaScript does not have any further lexical or block scoping. A variable is declared on the global scope like so: zombiesKilled = 10; A variable is declared on the function scope as follows: var antiPokemonSpray = true; 1 www.it-ebooks.info Chapter 1 ■ JavaSCript iS Not the LaNguage You thiNk it iS That’s not entirely true, actually. Using the var keyword attaches the variable to the nearest closing scope, so using it outside any function will declare the variable on the global scope as well. Note that the lack of any block-level scoping can cause bugs that are pretty hard to track down. The simplest example of this is the use of loop counters; for instance, for (var i = 0; i < 10; i++) { console.log(i); } console.log(i); That last logging statement won’t output null or undefined, as you might expect. Because of the lack of block scope, i is still defined and accessible. This can cause problems if you don’t explicitly define the value of your loop counter variables on every reuse. Global scope is something to be avoided in JavaScript. Not only do you have all the usual reasons, such as code modularity and namespacing issues, but also JavaScript is a garbage-collected language. Putting everything in global scope means that nothing ever gets garbage collected. Eventually, you’ll run out of memory, and the memory manager will constantly have to switch things in and out of memory, a situation known as memory thrashing. Declaration Hoisting Another concern with variable declarations is that they’re automatically hoisted to the top of the current scope. What do I mean by that? Check this out: var myHealth = 100; var decrementHealth = function() { console.log(myHealth); var myHealth = myHealth - 1; }; decrementHealth(); So, you would think that this would • output 100 • declare a new, function-scoped variable, myHealth, shadowing the globally scoped variable myHealth • set the function-scoped myHealth to 99 And, it would be totally reasonable to think that. Unfortunately, what you actually output is undefined. JavaScript will automatically lift the declaration of myHealth to the top of the function, but not the assignment. After the JavaScript engine gets done with that, here is the code you’re actually left with: var myHealth = 100; var decrementHealth = function() { var myHealth; console.log(myHealth); myHealth = myHealth-1; }; 2 www.it-ebooks.info Chapter 1 ■ JavaSCript iS Not the LaNguage You thiNk it iS Suddenly, that undefined output makes sense. Be careful! Declare all your variables up front so that this scenario doesn’t catch you unawares, and make sure they have sane default values. As a further illustration, let’s take a look at the following example: var myHealth = 100; var decrementHealth = function(health) { var myHealth = health; myHealth--; console.log(myHealth); }; decrementHealth(myHealth); console.log(myHealth); This will output 99 first, then 100, because you’re setting myHealth to the value of health inside the function rather than setting by reference. JavaScript Typing and Equality Now that you understand the basics of variables, let’s talk about what types of values those variables can take. JavaScript is a loosely typed language, with a few base types and automatic coercion between types (for more information, see the section “Type Coercion”). Base Types JavaScript only has a few basic types for you to keep in mind: 1. Numbers 2. Strings 3. Booleans 4. Objects 5. Arrays 6. null 7. undefined Numbers Numbers are fairly self-explanatory. They can be any number, with or without a decimal point or described using scientific notation, such as 12e-4. Most languages treat at least integers and floating-point numbers differently. JavaScript, however, treats all numbers as floating point. It would take too long to go into the potential problems with floating-point numbers here. Suffice it to say that if you’re not careful, you can easily run into floating-point errors. If you want to learn more about the pitfalls of floating-point arithmetic, I’d recommend checking out the Institute of Electrical and Electronics Engineers (IEEE) spec IEEE 754: Standard for Binary Floating-Point Arithmetic. 3 www.it-ebooks.info Chapter 1 ■ JavaSCript iS Not the LaNguage You thiNk it iS The two additional values numbers can take on are Infinity and NaN. That’s right, NaN is a number. (for more information, see the section “Equality Checking”). Strings Strings are quite a bit simpler. As in most languages, you can treat a string like an array of characters. However, strings are also objects, with numerous built-in properties and methods, such as length and slice: > "example string"[0] "e" > "example string".length 14 > "example string".slice(7) " string" I should point out that what I’m doing in the previous example is particularly bad. The memory behavior of where hard-coded strings are allocated isn’t part of the language specification. Being allocated on the global heap is actually one of the better scenarios. Depending on the browser, each individual use could be allocated separately on the heap, further bloating your memory. Booleans Booleans, as in most languages, can take on the values true and false. Both are reserved keywords in JavaScript. The main difference here between JavaScript and many other languages lies in which values can be coerced to either true or false (for further details, see the section “Truthiness,” later in this chapter). Objects Objects are the bread and butter of JavaScript, but they behave a bit differently from those in several other languages. In many ways, objects are similar to dictionaries in modern interpreted languages: x = {}; Curly braces indicate that you’re defining an object. Nothing inside suggests that this is the empty object. You can assign key-value pairs to an object like so: player = { health: 10 }; Pretty simple, really. You can assign multiple key-value pairs to an object by separating them with a comma: player = { health: 10, position: { x: 325, y: 210 } }; Note in this example that you’re assigning another object to the position property of player. This is entirely legal in JavaScript and incredibly simple to do. 4 www.it-ebooks.info

Description:
HTML5 Game Development Insights is a from-the-trenches collection of tips, tricks, hacks, and advice straight from professional HTML5 game developers. The 24 chapters here include unique, cutting edge, and essential techniques for creating and optimizing modern HTML5 games. You will learn things suc
See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.