PROFESSIONAL HTML5 Mobile Game Development Diving In -MAPDF.net

PROFESSIONAL HTML5 Mobile Game Development Diving In -MAPDF.net 

⊲ CHAPTER 1: Flying Before You Walk
⊲ CHAPTER 2: Making It a Game
⊲ CHAPTER 3: Finishing Up and Going Mobile

Flying Before You Walk
WHAT’S IN THIS CHAPTER?
➤ Creating the HTML5 for a game
➤ Loading images and drawing on canvas
➤ Setting up your game’s structure
➤ Creating an animated background
➤ Listening for user input

WROX.COM CODE DOWNLOADS FOR THIS CHAPTER
The wrox.com code downloads for this chapter are found at www.wrox.com/remtitle
.cgi?isbn=9781118301326 on the Download Code tab. The code is in the chapter 01
download and individually named according to the names throughout the chapter.
INTRODUCTION
Games have long been a medium that pushes technology to its limits. This book continues that
proud tradition by taking the core technologies of the web—HTML, CSS, and JavaScript—and
pushing them to the edges of their capabilities and performance. HTML5 as a game medium has
come a long way capability-wise in a short amount of time, and many people believe in-browser
gaming will be one of the primary distribution mechanisms for games in the coming years.
Even though it’s not an environment originally designed for creating games, HTML5 is actually
a nice, high-level environment for doing just that. So, in lieu of trying to abstract away all the
boilerplate by building an engine immediately, you can get right to the good stuff: a one-off game
built from the ground up on HTML5—a top-down 2-D space shooter called Alien Invasion.

BUILDING A COMPLETE GAME IN 500 LINES
To drive home the point of how easy it is to build games in HTML5, the inal game you build in the
irst three chapters contains fewer than 500 lines of code, all without using any libraries.
Understanding the Game
Alien Invasion is a top-down 2-D shooter game built in the spirit of the game 1942 (but in space) or
a simpliied version of Galaga. The player controls a ship, shown at the bottom of the screen, lying
the ship vertically through an endless space ield while defending Earth against an incoming hoard
of aliens.
When played on a mobile device, control is via left and right arrows shown on the bottom left of the
screen, and a Fire button on the right. When played on the desktop, the user can use the keyboard’s
arrow keys to ly and the spacebar to ire.
To compensate for all the different screen sizes of mobile devices, the game resizes the play area to
always play at the size of the device. On the desktop it plays in a rectangular area in the middle of
the browser page.
Structuring the Game
Nearly every game of this type consists of a few of the same pieces: some asset loading, a title
screen, sprites, user input, collision detection, and a game loop to tie it all together.
The game uses as few formal structures as possible. Instead of building explicit classes, you take
advantage of JavaScript’s dynamic typing (more on this in the section “Building Object-Oriented
JavaScript”). Languages such as C, C++, and Java are called “strongly typed” because you need to
be very explicit about the type of parameters that you pass around to method. This means you need
to explicitly deine base classes and interfaces when you want to pass different types of objects to
the same method. JavaScript is weakly (or dynamically) typed because the language doesn’t enforce
the types of parameters. This means you deine your objects more loosely, adding methods to each
object as needed, without building a bunch of base classes or interfaces.
Image asset handling is dead simple. You load a single image, called a sprite sheet, that contains all
your game’s sprite images in a single PNG and execute a callback after that image loads. The game
also has a single method for drawing a sprite onto your canvas.
The title screen renders a sprite for the main title and shows the same animated starield from the
main game moving in the background.
The game loop is also simple. You have an object that you can treat as the current scene, and you
can tell that scene to update itself and then to draw itself. This is a simple abstraction that works for
both title and end game screens as well as the main part of the game.
User input can use a few event listeners for keyboard input and a few “zones” on your canvas to detect
touch input. You can use the HTML standard method addEventListener to support both of these.
Lastly, for collision detection, you punt the hard stuff and just loop over the bounding boxes of each
of the objects to detect a collision. This is a slow and naive way to implement collision detection,

Adding the Boilerplate HTML and CSS ❘ 5
but it’s simple to implement and works reasonably well as long as the number of sprites you check
against is small.
The Final Game
To get a sense of where the game is headed, check out Figure 1-1,
and visit http://cykod.github.com/AlienInvasion/ on both
a desktop browser and whatever mobile device you have handy.
The game should run on any smartphone that supports HTML5
canvas; however, canvas performance on Android versions
before Ice Cream Sandwich is poor.
Now, it’s time to get started.
ADDING THE BOILERPLATE HTML
AND CSS
The main boilerplate for an HTML5 ile is minimal. You
get a valid HTML ile with a <canvas> element inside of a
container centered on the page, as shown in Listing 1-1.
LISTING 1-1: Boilerplate game HTML
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<title>Alien Invasion</title>
<link rel="stylesheet" href="base.css" type="text/css" />
</head>
<body>
<div id='container'>
<canvas id='game' width='320' height='480'></canvas>
</div>
<script src='game.js'></script>
</body>
</html>

6 ❘ CHAPTER 1 Flying BeFore you Walk
You can simply copy the CSS code verbatim to the top of base.css.
Next, you need to add two additional styles to the CSS ile, as shown in Listing 1-2.
LISTING 1-2: Base canvas and container styles
/* Center the container */
#container {
padding-top:50px;
margin:0 auto;
width:480px;
}
/* Give canvas a background */
canvas {
background-color: black;
}
The irst container style gives the container a little padding at the top of the page and centers its content
in the middle of the page. The second style gives the canvas element a black background.
GETTING STARTED WITH CANVAS
You hopefully noticed a canvas tag in the middle of the HTML on the page (as shown in
Listing 1-2):
<canvas id='game' width='320' height='480'></canvas>
This is where all the action for the game takes place—so much exciting stuff you can do in such an
unassuming tag.
The tag has an id for easy reference along with a width and height. Unlike most HTML elements,
you generally never want to add a CSS width and height onto canvas elements. Those styles visually
resize your canvas but do not affect the pixel dimensions of the canvas, which is controlled by
the width and height on the element. Most of the time you should leave these alone.
Accessing the Context
Before you can do any drawing onto canvas, you need to fetch the context from the canvas element.
The context is the object that you actually make API calls against (not the canvas element itself.)
For 2-D canvas games, you can pull out the 2-D context, as shown in Listing 1-3.
LISTING 1-3: Accessing the rendering context
var canvas = document.getElementById('game');
var ctx = canvas.getContext && canvas.getContext('2d');
if(!ctx) {
// No 2d context available, let the user know
alert('Please upgrade your browser');

6 ❘ CHAPTER 1 Flying BeFore you Walk
You can simply copy the CSS code verbatim to the top of base.css.
Next, you need to add two additional styles to the CSS ile, as shown in Listing 1-2.
LISTING 1-2: Base canvas and container styles
/* Center the container */
#container {
padding-top:50px;
margin:0 auto;
width:480px;
}
/* Give canvas a background */
canvas {
background-color: black;
}
The irst container style gives the container a little padding at the top of the page and centers its content
in the middle of the page. The second style gives the canvas element a black background.
GETTING STARTED WITH CANVAS
You hopefully noticed a canvas tag in the middle of the HTML on the page (as shown in
Listing 1-2):
<canvas id='game' width='320' height='480'></canvas>
This is where all the action for the game takes place—so much exciting stuff you can do in such an
unassuming tag.
The tag has an id for easy reference along with a width and height. Unlike most HTML elements,
you generally never want to add a CSS width and height onto canvas elements. Those styles visually
resize your canvas but do not affect the pixel dimensions of the canvas, which is controlled by
the width and height on the element. Most of the time you should leave these alone.
Accessing the Context
Before you can do any drawing onto canvas, you need to fetch the context from the canvas element.
The context is the object that you actually make API calls against (not the canvas element itself.)
For 2-D canvas games, you can pull out the 2-D context, as shown in Listing 1-3.
LISTING 1-3: Accessing the rendering context
var canvas = document.getElementById('game');
var ctx = canvas.getContext && canvas.getContext('2d');
if(!ctx) {
// No 2d context available, let the user know
alert('Please upgrade your browser');

8 ❘ CHAPTER 1 Flying BeFore you Walk
Drawing Images
Alien Invasion is an old-school, top-down 2-D shooter game with retro-looking bitmap graphics.
Luckily canvas provides an easy method called drawImage that comes in a couple of lavors, depending
upon whether you want to draw an entire image or just a portion of an image.
The only complication is that, to draw those graphics, the game needs to load the image irst. This
isn’t a huge deal because browsers are handy at loading images; however, they load them asynchronously,
so you need to wait for a callback to let you know that the image is ready to go.
Make sure you have copied the sprites.png ile over from the book assets for Chapter 1 into an
images/ directory underneath your current game, and then add the code from Listing 1-4 to the
bottom of your startGame function.
LISTING 1-4: Drawing images with canvas (canvas/game.js)
function startGame() {
ctx.fillStyle = "#FFFF00";
ctx.fillRect(50,100,380,400);
// Second, semi-transparent blue rectangle
ctx.fillStyle = "rgba(0,0,128,0.8);";
ctx.fillRect(25,50,380,400);
var img = new Image();
img.onload = function() {
ctx.drawImage(img,100,100);
}
img.src = 'images/sprites.png';
}
If you reload the page, you should now see the sprite sheet layered
on top of your rectangles. See canvas/game.js in the chapter
code for the complete code. You can see the code irst waits
for the onload callback before trying to draw the image onto the
context and then sets the src after setting up the callback. The
order is important because Internet Explorer does not trigger the
onload callback if the image is cached if you reverse the order of
the two lines. You can see the results—admittedly not pretty—in
Figure 1-2.
This irst example uses the simplest drawImage method—one
that takes an image and an x and y coordinate and then draws
the entire image on the canvas.
Modify the drawImage line to read as follows:
var img = new Image();
img.onload = function() {
ctx.drawImage(img,100,100,200,200);
}
img.src = 'images/sprites.png';
FIGURE 1-2: The spritesheet and
drawn rectangles.

........................

www.MAPDF.net

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

木合塔尔 麦麦提

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值