Chapter 7. HTML5 and Mobile Game Development

In this last chapter we will take a look at the ever so important concept of not only developing for multiple browsers and platforms, but also of developing an application with multiple devices in mind. It used to be that web development was all about supporting multiple browsers. Then it became all about taking advantage of the latest technologies available and creating applications that resembled a native desktop application. Today, we must not only remember those same concepts that allow us to make our applications available to as many people as possible, but we must also remember that the standard desktop computer is not the only machine accessing our web applications.

While creating an HTML5-based game or application, we must be able to envision our users connecting through the desktop computer, net-books, HTML5-ready video game systems, smart phones, tables, television sets, and soon their smart watches, smart glasses, and possibly their smart toasters, fish tanks, and so on. Needless to say, there are quite a few differences between these devices, other than their size, shape, and suggested retail price.

As we develop the last game in this book, lets take a look at some of the most important concepts related to mobile game development with HTML5. We'll first look at fundamental differences between a desktop machine and a mobile device (specifically, a smart phone and a tablet). The two HTML5-related APIs discussed in the chapter are media queries (which allows us to adjust CSS properties based on the current state of the device viewing the application) and JavaScript touch events, with their corresponding event handlers. Finally, we'll conclude the chapter with a discussion on how to go about developing and optimizing a game for a desktop browser as well as a mobile device, with a single code base.

Desktop versus mobile

At first sight, the careless web developer might be led to believe that, because many of today's smart phones are in fact quite a lot smarter than most fifth graders, that their fancy web applications and games will run just fine on a mobile device. Do not be deceived! Although it is true that your smart phone is indeed smarter than you were when in fifth grade (in fact, most not-so-smart phones today have more computer power than the hardware that NASA used to take Neil A. Armstrong, Michael Collins, and Edwin E. Aldrin to the moon in 1969), it is in many instances no match to the average desktop computer from which most people surf the internet and play games online.

There are several significant differences between a desktop browser and a mobile browser. For this reason, we need to develop our applications with these differences in mind. After all, no matter how large the group of people only using the internet strictly from a mobile device or from a desktop browser, we have no reason to limit our reach to only one of those groups.

One key aspect of mobile-friendly development that we must keep in mind, which doesn't always apply to games, is that one's mobile strategy is often inherently different from a desktop strategy for reasons beyond hardware limitations and differences. For example, use case on a mobile device is substantially different than the use case on a desktop version of a journal application. Since it is much harder and slower to type on a small device, users are less likely to spend hours typing a journal entry on a phone application as opposed to its desktop counterpart, where a full-sized keyboard is available. Thus, the entire mobile experience must be considered with a different persona in mind.

Finally, because the human-computer interaction is different in a mobile device, the presentation of the application must be considered with these features in mind. For example, while navigating a website, most people would generously move the mouse cursor about the screen in an attempt to discover what can be clicked and what can be interacted with. Every time an action element is hovered, the mouse pointer changes (normally from an arrow icon to a pointing index finger) hinting to the user that an action can be initiated by clicking on such item. On a mobile device, however, no such thing exists. Thus, the design must take this into account, so that users aren't confused, intimidated, or worse yet, hesitant to use your game or application.

The rest of this section will present a few major implementation considerations for your mobile strategy as well as a couple of current best practices. Both sections apply equally well to mobile games and mobile applications (non-gaming applications, that is). Albeit not extensive, this list of considerations and best practices should be sufficient to get you thinking in the right direction, and pointed towards a successful mobile campaign.

Major implementation considerations

Perhaps the most distinguishing feature that sets a mobile device apart from a desktop computer is the fact that the mobile device is always accessible. Once the user has left his or her house, the desktop machine is parked until possibly many hours later. The mobile device, on the other hand, can be as far away from the user as his or her pocket. So at any moment, the user can pull out the mobile device and start playing your game or using your application.

Very importantly, a continuation of this always accessible use case is that a user will play your game for a very small amount of time—while waiting for the elevator, while standing in line at the store, or while trying to drown out an awkward moment during a first date. Thus, your game must accommodate these brief, very brief, playing sessions and it must do so in a way that the player can still make progress in the game while playing it in sessions of 30 to 120 seconds at a time.

Some important considerations for your mobile game that are more related to the physical nature of mobile devices include its limited screen size, the possibility to change screen orientation effortlessly, limited computing power (relative to a desktop computer, of course), limited battery power, and browser differences (no, those haven't gone away yet on mobile devices, either).

Screen size and orientation

The most obvious difference between a desktop computer and a mobile device is its size. Even though most modern devices can simulate large screen resolutions, the physical screen size is still rather limited. Not only that, but also at any moment the user can rotate the device sideways, expecting a responsive feedback of some sort from the application.

In web design in general, the standard solution to the problem of smaller and varying screen sizes is a technique called responsive design. The main tool used today to implement responsive design is the new CSS media query API (which we discuss later in the chapter). Simply put, this API allows us to load different stylesheets or sets of CSS rules based on, among other things, screen size, proportions, and orientation.

For example, we can define a CSS stylesheet for the case when the screen is wider than it is taller (which, by definition, would make it a landscape viewport) and have a second style sheet designed for the case when the screen is taller than it is wider (making it a portrait view). Media queries would allow us to automatically and dynamically load one of these two stylesheets based on the current screen state. That is, if the user was to manually resize the browser window, the style sheet would trigger in real time.

As for screen orientation changes, DOM-based web applications have it easier, because the browser itself if able to rotate everything, so it faces the right direction. On a canvas-based application (either 2D canvas or WebGL), a screen rotation also rotates the browser's coordinate system, but not the canvas'. Thus, if you want a particular game to play horizontally on a landscape view, and vertically on a portrait view, you'll need to manage the rotation of the canvas' coordinate system by hand.

Most importantly, however, is the fact that when designing a mobile-friendly, or a mobile version of a game, the screen size will be significantly smaller. That means that fewer elements can be crammed into a particular view. Less information needs to be presented, since less information can be conveyed at once.

The two common solutions to this problem are to develop one application with two separate presentation layers (or two separate views or templates), only serving the view that's appropriate to the device requesting it (serving the mobile template when a template accesses the application and the full template when a desktop browser requests the application) and developing a single application with a single template, but making this template responsive, as described previously. The less popular alternative is to develop two separate applications altogether, where each application focuses on a given paradigm (mobile and desktop).

Normally, the mobile template is a shrunk down version of the full template where not all elements are necessarily displayed, as represented by the following illustration:

Screen size and orientation

Computing power

As mentioned before, today's mobile devices have gotten quite powerful. Even more amazing is the fact that the tendency is for them to continue to improve, jamming more computing power into less physical space. However, the best smart phone today is no match against even an average power gaming PC. For most web applications, this difference can often be neglected but certainly not for more complex games.

One specific disadvantage that mobile devices have against desktop computers in this area is that the gap between the computing power of a lower-end mobile device and an average mobile device is quite large, as compared to a low-end desktop computer and a mere average one. Thus, when considering the capabilities of your game's users, remember that a large amount of those players will have very limited devices.

Battery life

Believe it or not, the most used feature of a smart phone is, well, to make and receive phone calls. With such an important function being the mobile device's primary use, it would be quite tragic to keep the device from performing such a task because a game uses up all of the device's battery power. For this reason, one very important characteristic of a mobile application (including games and mobile web applications) is how well it conserves power.

The more data the application needs to process, the more electricity it will require to do so. If the game spends much of its time performing complex calculations, it is likely to quickly drain the device's battery sooner than one would like it to. It is imperative that your mobile games use the least possible amount of power so that the player can enjoy the game as much as possible, while still saving enough battery power so that the device can serve its most fundamental purpose—to make phone calls.

Browser differences

If you thought all your browser compatibility issues would go away once you started focusing your web development efforts on mobile devices, think again. Not only are there differences between the various mobile browsers themselves (just as there are differences on their desktop counterparts), but also not every HTML5 API and feature available on a given desktop browser is available on the same browser's mobile version.

Some features are in fact available on a mobile browser, but the performance is still a very long way from being acceptable. One simple example that we will see in the game developed in this chapter is CSS animations. Depending on how creative you get with the animation, the mobile browser might have a very hard time handling the animation, while on a desktop browser the computations and rendering power needed to display the animation smoothly and consistently are quite trivial.

In summary, when defining the concrete way in which your mobile application is to be implemented, keep in mind that some APIs and features will simply have to be thrown out, lest the application performs at unacceptable levels.

Best practices

Now that you're ready to take the theory just discussed, where the rubber meets the road, let's discuss a few best practices on how to do just that. While a complete book could be dedicated to this topic, the following selection covers what I believe to be the top five most important best practices for mobile web development. Again, these concepts apply to generic web applications as well as games.

Degrade gracefully and enhance progressively

Up to a couple of years ago, any discussion about adding new and cutting edge functionality to a web application was built around the topic of graceful degradation. More recently, that ideology has shifted more towards the other end of the spectrum, where the suggested way of building multiplatform and multidevice applications is with progressive enhancement.

In this context, graceful degradation refers to building the full-blown application first (the latest and greatest desktop browser), then scaling it down so that it works on a less capable browser as well as on mobile devices. Similarly, progressive enhancement refers to building the mobile version of the application first, then making it work on the desktop browser. Whichever approach is taken, the end result is the same—one application that functions equally well on both platforms.

While much can be said about both of these approaches, in practice none is particularly better than the other. The only difference is simply where you start. Hopefully, the application is well planned for, so that each version is already envisioned before construction begins, so that starting at either end will take the application to the same place. Normally, however, the ideal approach to take depends largely on the type of project in question.

In the case of most games, as was indeed the case with the 2D space shooter game built for this chapter, it is much easier to develop the desktop version first then remove whatever functionality is not supported by, or appropriate for, mobile devices.

For example, the main rendering loop of our game is based on the new requestAnimationFrame function. Now, not all browsers expose this function yet, while others expose it through a different interface. Gracefully degrading this functionality would mean to use the function where available and use a fallback where it isn't available.

window.requestAnimationFrame = (function() {

  // Check if the unprefixed version is present
  if (window.requestAnimationFrame) {
    return window.requestAnimationFrame;
  }

  // Check for WebKit based implementation
  if (window.webkitRequestAnimationFrame) {
    return window.webkitRequestAnimationFrame;
  }

  // Check for Mozilla based implementation
  if (window.mozRequestAnimationFrame) {
    return window.mozRequestAnimationFrame;
  }

  // Check for Microsoft based implementation
  if (window.msRequestAnimationFrame) {
    return window.msRequestAnimationFrame;
  }

  // Check for Opera based implementation
  if (window.oRequestAnimationFrame) {
    return window.oRequestAnimationFrame;
  }

  // If nothing else, simulate the functionality with
  // something similar - a custom timer
  return function(callback) {
    var fps = 1000 / 60;
    var timestamp = Date.now();

    setTimeout(function(){
      callback(timestamp);
    }, fps);
  };
})();

On the other hand, a progressive enhancement approach would start out with the lowest common denominator first, not promising any special bells and whistles to anyone, but adding those in as permitted by the client technology.

For example, suppose we want to make extensive use of CSS animations. Specifically, we wish to use a very large image for the background, then animate its position and size continually using keyframe animation. On a mobile device, this could consume a lot of processing power, causing severe performance problems. Thus, we decide not to use these animations in such cases.

Enhancing the application progressively in this case would mean that we start out with a static image for the background. The CSS file defining the animation and applying it to the application is not loaded by default.

// ---------------------------------
// Default Stylesheet: style.css
// ---------------------------------
.background-img {
  background: url("/img/bg.png");
}

// ---------------------------------
// HTML Template: template.html
// ---------------------------------
<div id="container" class="background-img"></div>

Once that minimum functionality is in place, we can test the environment in order to determine if we should load the CSS file, injecting the more robust functionality.

// ---------------------------------
// Enhanced Stylesheet: enhanced.css
// ---------------------------------

@-webkit-keyframes animagedBg {
  from {
    background-position: 0 0;
  }
  to {
    background-position: 1300% 600%;
  }
}

.anim-background {
  -webkit-animation: animagedBg;
  -webkit-animation-duration: 500s;
  -webkit-animation-timing-function: linear;
  -webkit-animation-iteration-count: infinite;
}

// ---------------------------------
// JavaScript Detection: main.js
// ---------------------------------

// Returns true if the browser is mobile
function isMobile(userAgent) {
  var mobileAgents = [
    "ANDROID",
    "BLACKBERRY",
    "IPHONE",
    "IPAD",
    "IPHONE",
    "OPERA MINI",
    "IEMOBILE"
  ];

  return mobileAgents.indexOf(userAgent.toUpperCase()) >= 0;
}

var mobile = isMobile(navigator.userAgent);

// If the browser is not mobile, add enhanced CSS functionality
if (!mobile) {
  var container = document.querySelector("#container");
  container.classList.add("anim-background");
}

Now, it wouldn't be particularly difficult to build the game with the animated background first, then remove it when a particular device was detected. There wouldn't necessarily be any added value taking this approach either.

In summary, whatever approach makes more sense to your specific application and design goals and objectives, the key principle is to keep user experience in mind. Never present the user of your game or application with an unusable product or feature. Either downgrade the feature to something useful or upgrade it when you are sure that the user's environment can make proper use of the feature.

Finger-friendly design

Another very important design consideration that is so easy to overlook is the size of the various elements. Although making text large enough is important, this is somewhat easier to get right. Plus, text size is fairly easy to adjust dynamically, so users can tweak things until they're comfortable with the exact size of the text in your application. However, coming from the point-and-click world, where action targets are big enough if the mouse pointer can fit on top of it, we may not realize that different people have vastly different finger sizes. Nothing can possibly be more frustrating to a big-fingered user, than to miss a click target because the target is too small. When the first touch-sensitive mobile applications came out several years ago, users probably considered carrying a finger sharpener along with their device, so that those tiny touch targets could be reached.

In the following illustration, the screenshot on the left is an example of items that are too small for a user to touch, as well as items that are too close together. The better solution, as shown on the screenshot on the right, makes the interface more forgiving and harder for the user to mess up.

Finger-friendly design

If you look at the developer guides published by the various mobile platform makers, you will find specific pixel dimensions that are suggested as the minimum size for widgets that can be touched as well as minimum distances between two or more touchable elements. While there is no perfect size of any particular widget, we must always design with this issue in mind.

Save battery life

No matter how amazing your mobile game might be, the minute that users realize that the game is rudely demanding on their device's battery, the game will immediately be frowned upon. If the user is running low on power, but they know that your game is very friendly with power consumption, your application will definitely get extra love.

Now, the main source of energy inefficiencies in mobile apps is extensive, unnecessary hardware use. For example, if an application pulls the GPS multiple times per second, it will probably run down the battery fairly quickly. However, in an HTML5 application, direct hardware access is not as readily available.

In the case of a web application, the main way to save energy is to do as much caching as possible. The main point of caching here would be to avoid extra network activity. Not only would the extra processing require more energy, but it would also force the user to spend what is often limited bandwidth. As an added bonus, caching would also make your application behave much faster.

Plan for offline

A very large amount of mobile gamers today have a limited amount of internet access from their mobile device. Any extra use of that precious data plan might be a costly deal for the user. As a result, many users actively disable internet access on their device. As a result of that, you should never make the assumption that your games will have continuous access to the internet.

Again, the best solution to this use case is to use caching to your benefit. First, by making fewer server round trips, even if each batch is larger, you will be saving expensive bandwidth that the user is trying to save. Second, the application can seem much faster and more responsive if HTTP requests are saved up for a moment when the application is not doing anything meaningful (such as displaying a game-related message or waiting for the user to input information).

Offering a desktop version

There are many reasons why a user might want to checkout a mobile application's non-mobile version. Perhaps it is because of missing functionality, maybe the user has a good enough mobile device that can actually handle the full version just fine or maybe the user wants to access the full version from a mobile device just out of curiosity. Whatever the reason, adding a link to the full-sized version of your application is perhaps the easiest thing you can do, so why not do it for the minority of users who might actually use it!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.131.38.14