How to Make A Simple HTML5 Game With Enchant.js
This is a post by Tutorial Team member Guts Rodsavas, an iOS development trainer at Software Park Thailand and game developer at Coffee Dog Games. Are you curious about developing cross-platform mobile games that work in a web browser? Well, as you probably know, Apple doesn’t allow Flash to run on iOS devices, and Adobe […] By .
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Contents
How to Make A Simple HTML5 Game With Enchant.js
60 mins
- Introducing enchant.js
- Setting Up the Environment
- Preparing Your Project Structure
- Why Hello There, Ocean!
- Node, Scene and Game: The Basic Concepts
- Object-Oriented Style With enchant.js
- Who Let the Penguin Out!
- A Closer Look at Sprites
- Basic Animation
- Touch Detection
- Ice, Ice Baby
- Collision Detection
- Tally the Score
- A Little Water Music
- Every Penguin Has His Day
- Testing Your Game on Mobile Browsers
- Prepare for iOS Device
- Where To Go From Here?
- Credits
Every Penguin Has His Day
You’re almost there! It’s time to make life challenging for your carefree penguin. He’ll be punished for hitting the ice with death, and when he dies, you’ll allow the player to restart the game.
Start by creating a SceneGameOver class. Add this code to the end of main.js, just as with all the other classes:
// SceneGameOver
var SceneGameOver = Class.create(Scene, {
initialize: function(score) {
var gameOverLabel, scoreLabel;
Scene.apply(this);
this.backgroundColor = 'black';
},
});
Like SceneGame, SceneGameOver is a subclass of the Scene class. You’ll be creating two labels to show on the screen. One label will say “Game Over”, and the other will report the final score.
You also set the background color of the scene this time, instead of using an image. Currently the color is set to black, but you can try other colors if you’d like.
Note: Instead of color names, you can also use hex codes or RGB color values. For example:
Note: Instead of color names, you can also use hex codes or RGB color values. For example:
this.backgroundColor = '#000000'; // Hex Color Code version
this.backgroundColor = 'rgb(0,0,0)'; // RGB value version
this.backgroundColor = '#000000'; // Hex Color Code version
this.backgroundColor = 'rgb(0,0,0)'; // RGB value version
Add the following code right after where you set the background color in SceneGameOver:
// Game Over label
gameOverLabel = new Label("GAME OVER<br>Tap to Restart");
gameOverLabel.x = 8;
gameOverLabel.y = 128;
gameOverLabel.color = 'white';
gameOverLabel.font = '32px strong';
gameOverLabel.textAlign = 'center';
This is straightforward: you create a label and adjust its style.
Next create a label to report the final score. Add the following code right after the previous code:
// Score label
scoreLabel = new Label('SCORE<br>' + score);
scoreLabel.x = 9;
scoreLabel.y = 32;
scoreLabel.color = 'white';
scoreLabel.font = '16px strong';
scoreLabel.textAlign = 'center';
Just as you did before, this will create a score label. The score variables come from the SceneGameOver constructor. This means that when you create an instance of this scene, you have to pass a final score to it.
Your labels are ready. It’s time to add them to the scene!
Add the following code immediately after the previous block:
// Add labels
this.addChild(gameOverLabel);
this.addChild(scoreLabel);
Finally, make the scene listen for the TOUCH_START event, so that players can restart the game by tapping on the screen. [TODO: Put this where?]
// Listen for taps
this.addEventListener(Event.TOUCH_START, this.touchToRestart);
SceneGameOver is missing a method for the touch handler. Fix that by adding it [TODO: Where?]:
touchToRestart: function(evt) {
var game = Game.instance;
game.replaceScene(new SceneGame());
}
This method does nothing but replace the current scene with SceneGame, meaning that the game will go back to SceneGame again.
Now that you have your SceneGameOver ready, let’s use it in the game!
Since the game will move to SceneGameOver when the penguin is hit by an ice boulder, modify your collision detection code to the following:
if (ice.intersect(this.penguin)){
.
.
.
// Add the following lines
// Game over
this.bgm.stop();
game.replaceScene(new SceneGameOver(this.score));
break;
}
The code stops the background music, and then tells the game to replace the current scene with an instance of SceneGameOver, using the current score as the argument for instantiation.
Save main.js and refresh your browser again. Let the penguin get hit by a boulder and watch the screen go black. Clicking on the game over screen should return you to the game.
Your game is finished! However, all the while you’ve been testing this game on your desktop browser. Isn’t the charm of enchant.js that you can run it on a mobile browser?
Let’s do that now!
Testing Your Game on Mobile Browsers
Before proceeding, note that for this to work, your machine needs to be running a web server.
While you can’t just type “localhost” into your mobile browser address bar to access your local server, you can access it through your local IP address.
There are many ways to get your desktop’s IP address. If you’re running Windows, you can follow this tutorial. On OS X, you can get it from Network Preferences.
Once you’ve got your local IP address in hand, you can access your game by using the same URL as on the desktop, but replace localhost with your local IP address.
For example, let’s say your local IP address is 10.10.10.10. If the URL to your game on your desktop is:
http://localhost/~Home/penguindive/
Then the URL on your mobile phone would be :
http://10.10.10.10/~Home/penguindive/
Prepare for iOS Device
If you try running the game from your retina display iOS device, you’ll notice that the game is really tiny:
There’s no way you’re playing that with your big human paws! :]
To fix this, open index.html and add the following line to the header section:
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1.0">
This sets the size of your game’s viewport. To understand more about the viewport, you can read the Apple Documentation on the subject. Simply put, the viewport is the area that determines how your content will be laid out in a mobile browser.
In enchant.js, the Game object will check to see if your game is running on a retina display device. If it is, it will modify this viewport meta tag and adjust the game size to appropriately, so you don’t have to worry about your game being displayed incorrectly on retina display devices.
One more thing you’ll notice on an iOS device is that your game isn’t really on the top left – there are some margins. Let’s fix this as well. Modify your HTML body in index.html to be as follows:
<body style=“margin: 0;”></body>
This sets the body margin to zero, leaving no white gap between the game and the top left of the browser window.
Now the only thing that is in your way is the address bar. Fortunately, you can get rid of it very easily.
Go to main.js and add this line after game.start():
window.scrollTo(0, 0);
On iOS, this line tells the browser to scroll down until the address bar is out of sight, giving you a nice full-screen effect.
Save main.js and run the game again. Here’s what it should look like on your device:
You can also view the game running on our web site here.