游戏邦在:
杂志专栏:
gamerboom.com订阅到鲜果订阅到抓虾google reader订阅到有道订阅到QQ邮箱订阅到帮看

列举开发者制作HTML5游戏的5个诀窍

发布时间:2013-06-20 17:19:55 Tags:,,,

作者:Kai Jäger

HTML5的强大之处在于其多用性——它并不局限于单一的用法。更重要的是,HTML5还很普遍,可以用于PC、手机、平板设备,甚至是厨房电器。

多用性及普遍性这两大优势,正是许多开发者对HTML5技术的兴趣所在,这其中又以游戏开发者最为典型。

幸运的是,现在有关HTML5游戏开发的文章已经颇为普遍。在此我将概括你在制作HTML5游戏之前应该考虑的一些事项。以下内容包括HTML5游戏开发框架,如何通过支持兼容智能手机和平板设备而获得更多用户,如何管理游戏内的状态,如何处理运行性能等问题。

最佳做法1:使用框架

使用HTML5编写简单的游戏很容易,但如果你要提高水准,就需要多下功夫确保游戏顺畅运行。

例如,当你用到大量图像、音效以及其他资源时,你的浏览器就要费些功夫才能从网络服务器中下载内容。你编写游戏时要考虑到这一点。因为图像和声音文件是异步加载,你的JavaScript代码会在你所有的资源已经加载之后才开始执行。这通常会造成一种图像“突然弹出”,而音效却出现滞后的情况。解决这一问题的好方法就是创造一个预紧器来推迟脚本执行,直到所有的资源都下载完成为止。

你很可能遇到的另一个问题是不同机器以及浏览器对你的游戏运行速度并不相同。虽然这并没有很好的解决方法,但你仍可确保动画和行动速度独立于游戏所运行的帧率。

最重要的是,每款游戏都需要许多使其合理运行的样板文件代码。所幸你并不需要亲自编写所有的这些代码。已经有大量框架允许你专注于游戏逻辑,无需顾虑所有与游戏顺畅运行相关的琐事。

这里要注意的是,你有许多可以选择的框架。例如ImpactJS等框架可用于辅助游戏开发过程的每个环节,而EaselJS等框架的专长则是与图像有关的内容。但主要还是由你来决定要选择哪种框架。在JavaScript世界中,选择一种框架通常意味着选择一种特殊的编程方式。

ig.module(
‘monster’
)
.requires(
‘impact.game’,
)
.defines(function(){

Monster = ig.Entity.extend({
eyes: 42
});

});

这方面的一个优秀典范就是ImpactJS,不但提供了展示图像或播放音效的抽象元素,还引进了其自身的对象和继承模式(如上所示)。

Ascend Arcade(from msdn)

Ascend Arcade(from msdn)

(Ascend Arcade在三个月内使用ImpactJS框架推出了3款游戏)

最佳做法2:考虑小型触屏设备

HTML5的一个最有说服力的卖点或许就是它适用于桌面PC、笔记本电脑、平板电脑,以及智能手机。

这一独特的跨平台特点是HTML5的本质属性,通常可以节省开发者的额外工作。但你还需要考虑一些事情……

SpyChase(from msdn)

SpyChase(from msdn)

(在Windows Phone 7 Mango平台运行的《SpyChase》)

最重要的是,不同设备的屏幕大小、分辨率和纵横比也不尽相同。如果你想让自己的HTML5游戏在移动设备上合理运行,你就要它们能够支持多种分辨率或者不超过800*480的WVGA帧尺寸。

此外,由于多数移动设备没有足够的屏幕尺寸一次性渲染整个网页,它们通常会采用一些不利于游戏编写的复杂缩放技巧。这可以使用视窗元标签来关闭。以下代码片断将导致你的游戏视窗占满屏幕所有的平筛实用面积。将参数“user-scaleable”设为“no”令移动浏览器的缩放功能失效,以免其与手指控制方式相冲突:

<meta name=”Viewport”
content=”width=device-width; user-scaleable=no; initial-scale=1.0″ />

当你的游戏在小屏幕设备上渲染成功时,你应该花点时间考虑输入问题。多数仅支持触控方式的设备都有一个虚拟键盘,但它们通常都会占据太多本可用于控制游戏角色的屏幕空间。如果触控输入方式没有问题,你就应该创建有限的虚拟键盘,其中仅含操作游戏所需的按钮(例如,方向键)。但是,最好还是发挥一些创意,选择无需额外屏幕元素的替代性控制方法。这方面的优秀典型是《Spy Chase》,玩家在游戏中要用一根手指驾驶一辆汽车(而你在现实生活中根本不可能如此)。

最佳做法3:自动保存玩家进程

网络浏览器会用site pinning等功能给予网页应用一些与常规桌面应用相同的状态。但是,关于让网站像应用一样运行还是新理念,网页托管客户端状态的概念也同样如此。你在关闭微软Word实例前可能会三思,但打开一个网页时就不那么谨慎了。多数时候,这并不是什么问题——多数网页或是根本没有状态,或是在服务器保持你的信息纪录。

网页游戏,则是另一回事了。由于JavaScript代码是在客户端执行,HTML5游戏通常在短暂的内存(如RAM)中保留游戏状态。若关闭浏览器窗口,你煞费苦心来之不易的高分就这样丢失了。

现在,你可能会认为足够谨慎的玩家不会轻易关闭自己已经玩了8小时的游戏,但总有意外情况,尤其是在多个标签同时运行或者电池突然没电之时。

简而言之:编写HTML5游戏时,最佳做法是经常保存玩家进程,允许玩家复原之前被关闭的网页数据。

那么你该从哪开始追踪玩家进程呢?在以前,显然要从服务器端的数据库或客户端的cookie入手。但这两种解决方案都不是很管用。用服务器端的方法,就得在任何信息需要存储或恢复时发出HTTP请求。而cookie方法只会给予极有限的空间,cookies的寿命长短很大程度上取决于浏览器配置。

一个更为可行的方案是使用HTML5 DOM存储。DOM存储可以让你通过一个类似于关键值(或者JavaScript自订对象)存储的界面,为每个网站节省数百万字节的数据。这非常方便,但在HTML5游戏环境中,你可能还得记住复杂的数据结构——那些DOM存储并不会自然支持的结构。

所幸,现代JavaScript拥有那些能够促成对象序列化的机制,并将其安装到名为JSON的紧缩记法中。使用这一方法,DOM存储还可用于记住任意信息。以下两个辅助功能描述了如何使用HTML5 DOM存储和恢复游戏状态,以及JSON功能如何植入ECMAScript5的过程:

function saveState(state) {
window.localStorage.setItem(“gameState”, JSON.stringify(state));
}

function restoreState() {
var state = window.localStorage.getItem(“gameState”);
if (state) {
return JSON.parse(state);
} else {
return null;
}
}

最佳做法4:使用分析器

开发游戏最大的挑战之一就是在添加更多功能时保持高帧率。

好消息在于,在过去几年中浏览器运行速度普遍加快,基于HTML5的游戏以60fps速度运行也已经成为现实。

但这并非易事。对IE9来说,这意味着要编写可使用多个CPU核,基于Direct2D完全硬件加速渲染管理的全新JavaScript引擎。换句话说:如果你已经在你的游戏工具中投入大笔资金,就可以充分利用IE9的优势。

IE 9(from msdn)

IE 9(from msdn)

(IE9绑定的JavaScript分析器有助于定位性能瓶颈)

对简单的游戏而言,这意味着你并不需要担心运行表现的问题。但由于HTML5是一个极具平台兼容性的技术,你可以向一系列设备和浏览器开发游戏,但其中有些平台运行速度可能并不如你的预期。即使你仅瞄准高性能的PC,运行表现也仍然是个问题。

如果你希望游戏以60fps的速度运行,你每帧渲染的时间就只有16毫秒而已。在你眨眼的功夫,你就得至少渲染6个完整的帧。这看似一个艰巨的任务……对于任何非小型游戏而言,事实的确如此。

幸运的是,这里有些工具能够解决问题。在IE9(或者IE10),按下F12键打开开发者工具,选中“分析器”标签并点击“开始分析”。

现在导航到你认为运行效果更佳的地方,给分析器30秒时间搜集数据,然后点击“停止分析”。你将看到一个关于游戏中每个函数消耗多少累积执行时间的概述。多数时候,你会发现有一系列函数占据了大部分的执行时间。优化这些函数会让你的成本大为攀升,并且当你在分析自己的代码时,缓慢的子程序会十分明显。

不要盲目相信自己的直觉——那些看起来很缓慢的代码也许在当今的JavaScript引擎中正快速执行。最佳优化方法是经常重新分析,并一直测量你对代码所做的改变是否对运行性能带来了积极影响。

Warimals(from msdn)

Warimals(from msdn)

(《Warimals》是基于HTML5的游戏,允许你同Facebook好友一起玩游戏)

最佳做法5:发挥创意

制作一款能够在浏览器中自然运行的游戏真是太棒了,如果能够用HTML5编写一款运行于你的浏览器之中的游戏那就更妙了。从技术角度来看HTML5很有趣,浏览器也是一个理想的游戏平台。

想想看……许多不同设备上都有浏览器,它们几乎都处于连网状态,它们是人们通过邮件、聊天和社交网络进行沟通的工具。作为网页游戏开发者,你可以制作有趣并且能够将全球各地用户连接起来的游戏。

如果你初涉HTML5游戏开发领域,也许会先采用仿制他人游戏的方法进行实践。这个做法并没有什么问题,但如果你想让游戏运行于“沟通应用”之内,最好是想出一些全新、富有创意的游戏理念。这方面的有趣典型就是《Warimals》(首批基于HTML5的Facebook游戏之一),玩家在其中可以扮演小狗或小猫,邀请Facebook好友同自己一起玩游戏。(本文为游戏邦/gamerboom.com编译,拒绝任何不保留版权的转载,如需转载请联系:游戏邦

Top 5 Best Practices for Building HTML5 Games, In Action!

By Kai Jäger

HTML5 is great because it’s versatile—it’s not specific to a single use case. More important, HTML5 is ubiquitous. It’s on your PC, your phone, your slate device—for all I know, it could even be on your kitchen appliances.

Take these two properties of HTML5—versatility and ubiquity—and it should become pretty clear why so many developers are inspired by it. And, as the  proverb goes, “When developers are inspired, they usually write games.” (Okay, maybe I just made up.)

Fortunately, deep-dive articles on HTML5 game development are now widely available. Instead, I’d like to give you an overview of things you should consider before you write a game using HTML5 and while you’re working on it.

What will you learn in this article? I’ll cover HTML5 game development frameworks, how you can reach more people by supporting smartphones and slate devices, how you should go about managing your in-game state, how to deal with performance issues, and how to make the most of the platform that is your browser.

So without further ado, here are the top 5 best practices for building HTML5 Games, in action! (“in action” added for dramatic effect).

Best practice #1: Use a framework

Writing simple games in HTML5 is easy, but as you up the ante, you need to do certain things to make sure that your game runs smoothly.

For example, when you use a lot of images, sound effects, and other resources, it will take some time for your browser to download it all from your web server. You’re in for a surprise if you don’t take this into account when writing your game. Because images and sound files are loaded asynchronously, your JavaScript code will start executing before all of your resources have been loaded. This often results in “popping” (images appearing out of the blue), and in sound effects not playing when they should. A good fix for this is to create a preloader that defers script execution until all resources have been downloaded.

Another problem you’ll likely run into is that different machines and/or browsers will run your game at different speeds. While there is nothing you can do about that, you should still make sure that animation and movement speeds are independent of the frame rate your game is running at.

Essentially, there’s a LOT of boilerplate code that every game needs in order to function properly. Fortunately, you don’t have to write all of this code yourself. There are now a variety of frameworks that allow you to focus on your game logic without having to worry about all the little (and big) things necessary to make your game run smoothly.

The only caveat with using a framework is that there are so many to choose from. Frameworks like ImpactJS for example are designed to help with almost every aspect of the game development process, while frameworks like EaselJS focus primarily on the graphics side of things. In the end, it’s up to you to pick the framework that you are most comfortable with. This may seem like a no-brainer, but in the JavaScript world, choosing a framework often implies opting into a particular style of programming.

ig.module(
‘monster’
)
.requires(
‘impact.game’,
)
.defines(function(){

Monster = ig.Entity.extend({
eyes: 42
});

});

A good example of this is ImpactJS, which not only provides abstractions for displaying graphics or playing sound effects but also introduces its own object and inheritance model as illustrated above.

Ascend Arcade delivered three games in three months using the ImpactJS framework.

Although a lot of HTML5 games now rely on some form of framework, many developers still go down the rocky road of trying to do everything themselves. While this might be a great learning experience, if you want to get things done in a reasonable amount of time, using frameworks is definitely the way to go. A good example of this is the great work of Ascended Arcade who managed to release three very enjoyable (and somewhat acclaimed) games in only three months using the ImpactJS framework.

Best practice #2: Consider small- and touch-screen devices

Maybe one of the most persuasive selling points of HTML5 is that it works on desktop PCs, laptop computers, slates and even smartphones (if you haven’t seen IE9 running on Windows Phone 7 Mango, check out this video).

This unique cross-platformness (take that, Webster’s dictionary!) is intrinsic to HTML5 and often requires little additional work from the developer. However, there are a couple of things you should consider…

SpyChase running on Windows Phone 7 Mango.

First and foremost, screen sizes can vary greatly between different device categories as can screen resolutions and aspect ratios. If you want your HTML5 games to work well on mobile devices, you should make sure they either support multiple resolutions or don’t exceed the WVGA frame size of 800×480.

Also, since most mobile devices lack the screen size to render an entire web page at once, they often employ sophisticated zooming and panning techniques that can be counterproductive when writing games. These can be turned off programmatically using the viewport meta tag. The following code snippet will cause your game’s viewport to occupy all of the available horizontal screen real estate. Setting the parameter “user-scaleable” to “no” tells the mobile browser to disable pinch-zooming, which otherwise often conflicts with finger-based game controls.

<meta name=”Viewport”
content=”width=device-width; user-scaleable=no; initial-scale=1.0″ />

Once your game renders okay on small-screen devices, you should also take a minute to think about input. Most touch-only devices have a virtual keyboard, but they tend to take up too much screen space to be useful in controlling game characters. If strictly touch-based input is out of the question, you should build a limited virtual keyboard with only the buttons you need for your game (e.g. the arrow keys). However, it’s best to be creative with alternative means of controlling your game that don’t require additional on-screen elements. A good example of this is the game Spy Chase, where you drive a vehicle with one finger (something you should not attempt in real life).

Best practice #3: Automatically save the player’s progress

With features like site pinning, web browsers attempt to give web applications the same status as regular desktop applications. However, the idea of websites functioning as applications is rather new, and so is the notion of web pages holding client-side state. You might think twice before closing an instance of Microsoft Word, but you might not be as careful with an open web page. Most of the time, this isn’t a problem—most web pages are either stateless or maintain a record of your information on the server.

Browser games, however, are a slightly different beast. Since JavaScript code is executed on the client, HTML5 games typically keep their game state in transient memory (aka RAM). Close the browser window and your hard-earned highscore is forever lost.

Now, you might argue that a sensible person would be cautious enough not to close the game they’ve been playing for eight hours, but accidents do happen, especially when multiple tabs are involved or batteries run out of juice.

To make a long story short: When writing HTML5 games, it’s an absolute best practice to save the player’s progress regularly and allow players to resume their game when returning to a web page they’d closed.

Now where should you keep track of players’ progress? In the past, the obvious place was either a server-side database or a client-side cookie. Neither solution is especially appealing. With a server-side approach, HTTP requests have to be made whenever information needs to be stored or retrieved. The cookie approach gives you very limited space to work with and the longevity of cookies greatly depends on the browser configuration.

A much more workable solution is to use HTML5 DOM storage. DOM storage lets you save several megabytes of data per website through an interface that resembles a key-value store (or a JavaScript expando object). It’s very convenient, but in the context of HTML5 games, you might also want to remember complex data structures—something that DOM storage does not natively support.

Fortunately, modern JavaScript implementations have mechanisms built in that enable the serialization of objects into a compact notation known as JSON. Using this approach, DOM storage can also be used to remember arbitrary information. The following two helper functions illustrate how game state can be stored and retrieved using HTML5 DOM storage and the JSON features built into ECMAScript5:

function saveState(state) {
window.localStorage.setItem(“gameState”, JSON.stringify(state));
}

function restoreState() {
var state = window.localStorage.getItem(“gameState”);
if (state) {
return JSON.parse(state);
} else {
return null;
}
}

Best practice #4: Use a profiler

One of the greatest challenges when developing a game is to maintain high frame rates as you add more and more features to it.

The good news is that browsers in general have become much faster over the last couple of years, and HTML5-powered games running at a constant 60 fps are already a reality.

It wasn’t easy. For Internet Explorer 9, this meant writing an all-new JavaScript engine that can use multiple CPU cores and a fully hardware-accelerated rendering pipeline based on Direct2D. In other words: If you’ve spent good money on your gaming rig, Internet Explorer 9 will make good use of it.

Internet Explorer 9’s integrated JavaScript profiler helps you locate performance bottlenecks.

For simple games, this means that you don’t have to worry about performance. But since HTML5 is platform agnostic, you’re potentially developing for a whole range of devices and browsers, some of which won’t be as fast as you’d like. Even if you’re only targeting high-powered PCs (something we said we wouldn’t do, remember?), performance can still become an issue.

If you want your game to run at 60 fps, you have no more than 16 milliseconds to render any individual frame. In the time it takes for you to blink, you have to render at least 6 complete frames. Now this may seem like a daunting task…and with any non-trivial game, it certainly can be.

Luckily, there are toolsthat can help you. In Internet Explorer 9 ( or 10 for that matter), hit the F12 key to open the developer tools. Select the “Profiler” tab and hit “Start profiling”.

Now navigate to where you feel performance should be better, give the profiler about 30 seconds to gather data, then hit “Stop profiling.” You will be presented with an overview of how much accumulated execution time is consumed by each of the functions of your game. Most of the time, you’ll find that there are a number of functions that take up the majority of the overall execution time. Optimizing these functions will give you the most bang for your buck and, when you analyze your code, slow subroutines will immediately stick out.

Don’t trust your instincts all too blindly though—code that looks slow might actually execute quite fast with today’s JavaScript engines. The best approach to optimization is to re-profile often and to always measure if the changes you make to your code actually have a positive impact on performance.

Gaming gone social: Warimals is based on HTML5 and allows you to playalongside your Facebook friends.

Best practice #5: Be creative!

To be able to write games that run natively in your browser is pretty awesome, but what’s even cooler is that HTML5 allows you to write games that RUN IN YOUR BROWSER! Not only is HTML5 interesting from a technology point of view, a browser is also a perfect platform for gaming.

Think about it…browsers exist on many different devices, they’re (almost) always online, and they’re a tool people use to connect with each other via email, chat and social networking. As a browser game developer, you can build games that are fun and bring together people from all over the world.

If you’re new to HTML5 game development, it might be tempting to write clones of games you’ve played offline. There is absolutely nothing wrong with this approach. But if you think of your game running inside a “communication application,” there’s a good chance you’ll come up with all-new, highly creative game ideas. An interesting example of this is Warimals, one of the first HTML5-based Facebook games. In Warimals, you can play either as dogs or kittens, and you can invite your Facebook friends to play along with you. What’s not to like?(source:microsoft


上一篇:

下一篇: