Quick Start (Regular)
Phaser is an excellent HTML5 game framework for PC and mobile HTML5 games.
This article will give you a quick introduction to game development (mobile). For anyone who wants to learn about game development or get into it, Phaser is undoubtedly a framework worth learning about.
Pay special attention to
Phaser is an excellent HTML5 game framework, but it does have its weaknesses. Now note the following two areas where Phaser can’t handle or is tricky to handle:
1. 3 d. If you want to learn how to make a cool 3D animation, learn three.js
2. Video (mobile terminal). If you need to embed video on your mobile page, use the native HTML5 tag Video. If you need a better extension to video, see Video.js
Then you can open up the example we are talking about in this article. After reading this example, you may say, “What’s the big deal? I can do this with Jquery animation.” Then I was told very clearly that comparing Phaser animations to Jquery animations is an insult to Phaser.
Well, that’s all for now. I personally feel that a case that is too complicated will confuse people and go against the purpose of our quick Start. After reading this article, you can open up the chapter of game development and feel free to describe the world as you like.
The code address
Said in the previous
First, in order to run our case properly, you need a local server. You may be wondering, why can’t we just drag index.html into a browser and run it?
Because it has to do with the protocol used to access the file. When you request anything on the network, you need to use HTTP, and the server can guarantee that you can only access the files you want. But when you drag the HTML file directly to the browser and run it directly, it is loaded through the local file system (file://), which has no concept of domains, no server-level security, and is just a raw file system.
Do you really want JavaScript to be able to load files from anywhere in the file system? The answer, of course, is no. Your computer certainly won’t agree.
Phaser loads resources: images, audio files, JSON data, or other Javascript files. In order to do this, it needs to run under the server.
If you don’t have a clue how to configure a local server to run HTML files, and that’s not the focus of this article, here’s a very simple way to do it:
1. Run the following command and press Enter: NPM install puer -g (if you do not have NPM, please install it on Baidu.) 2. After installing puer, run the following command in the case root folder that needs to be installed on the local server: Puer-p 9999 is as follows:
3. If puer runs successfully, the following information is displayed and the browser is automatically opened:
The following example is already loaded at http://localhost:9999/. Click on index.html to get Phaser up and running
Start the first step
First create our directory structure as follows:
The images in the IMG folder can be copied from the case code address, and you’ll see, hey, there’s a sprites. PNG image and a sprites. XML file on GitHub, which we’ll talk about later. Jquery.min. js and phaser.min.js under the js/libs file please prepare or copy from the case code address, then other files we need to keep blank so that we can quickly fill in later.
The second step
The first step is to quickly populate our index. HTML with the following:
<! DOCTYPE html> <html lang="en">
<head>
<meta charset="UTF-8"> <title>Phaser Quick Start (common version) </title> <meta name="viewport" content="Width =device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
</head>
<style>
html,
body {
width: 100%;
height: 100%;
font-family: "Helvetica Neue", Helvetica, STHeiTi, sans-serif;
overflow: hidden;
background: #fff;margin: 0; padding: 0; } .main { width: 100%; height: 100%; position: absolute; top: 0; left: 0; } .main img { width: 100%; height: 100%; } </style> <body> <! -- Canvas carrier for all animations on H5 page --> <div id="game-container"></div> <! Preload background to prevent preloaded resources from loading too long and leaving the screen blank for too long --> <div class="main">
<img src="img/bg.png" alt="">
</div>
</body>
<script src="js/libs/jquery.min.js"></script>
<script src="js/states/utils.js"></script>
<script src="js/libs/phaser.min.js"></script>
<script src="js/states/boot.js"></script>
<script src="js/states/preload.js"></script>
<script src="js/states/state1.js"></script>
<script src="js/states/state2.js"></script>
<script src="js/app.js"></script>
</html>Copy the code
In this file, all the animations are loaded on the element with the id of game-Container, and the element with the class of main is the preloaded background. If you don’t know the meaning of this element, you can see it later.
Then you’ll notice that we’ve imported jquery.min.js. You might be wondering, what is this for? Do YOU need to import Jquery when Phaser is being used? The answer is definitely not, Jquery was imported just to prove something later. Utils.js encapsulates some of the operations we’ll be using a lot later (full screen effects, zooming in and out)
Let’s focus on how our case works, starting with our five core files:
<script src="js/states/boot.js"></script>
<script src="js/states/preload.js"></script>
<script src="js/states/state1.js"></script>
<script src="js/states/state2.js"></script>
<script src="js/app.js"></script>Copy the code
The five files are executed in the following order:
app.js
-> boot.js
-> preload.js
-> state1.js
-> state2.js
In app.js, boot.js, preload.js, state1.js, state2.js are executed. Therefore, app.js needs to be imported after boot.js, preload.js, state1.js, and state2.js. Next, parse each of the five files one by one.
app.js
This file is the first one we implement for Phaser, and it does some game development configuration, including setting the path of our resources, mounting elements, adding scenes, launching scenes, etc.
The specific code is as follows:
(function() {
'use strict'// Set the resource directory (project root) var baseURI ='.. /.. '// Place the image directory in memory for global invocationlocalStorage.baseURI = baseURI // set $('#game-container') is equal to the height of the screen (written in native JS code here) document.getelementById ('game-container').style.height = document.body.clientHeight + 'px'Scale than var thewire = / / take screen window, devicePixelRatio / / get the width and height of the screen var w = document. The documentElement. ClientWidth | | document.body.clientWidth var h = document.documentElement.clientHeight || document.body.clientHeight //<meta name= because we set the meta header in index.html to prohibit zooming"viewport" content="Width =device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"< span style = "box-sizing: border-box; color: RGB (51, 51, 51); line-height: 20px; font-size: 14px! Important; word-break: normal;" Var ww = Ratio * w var hh = Ratio * h // The first two parameters are the width and height of the canvas element to be created by Phaser. The third parameter is the game rendering engine. Var game = new phaser. game (ww, hh, phaser. AUTO,'game-container'// Add scene game.state.add()'Boot', Boot)
game.state.add('Preload', Preload)
game.state.add('State1', State1)
game.state.add('State2', State2) // Start scene game.state.start('Boot')
})(window)Copy the code
Each line of code above has been commented so you can take a look at it and understand it if you have time, but for now we just need to know that app.js is just for configuring and launching our first scenario (boot.js).
The scene is the subject of our Phaser game development. All of the game animations we see are implemented in the scene. The scene can be a JS custom object or a function. Any preload, create, or update method is a valid scenario (there are five methods, along with the init and Render methods).
Init method: Some scenario initialization code can be written in this method and executed first.
Preload method: Used to load resources, which would be executed first if there were no init method.
Create method: The initialization and construction of the scene are performed after all the resources loaded in the preload method have been loaded.
Update method: An update function that is executed every frame of the game, usually once every 1/60 of a second.
Render method: called during every render cycle of the game to do some custom render work.
boot.js
This scene doesn’t show the user, just for loading the next scene (namely the preload. The preload scene js) the required resources, so the resources can not load too much, too much screen long black screen (black screen is actually the process of the scene is loaded resources, because this is the first scenario, not on the scene to help you load the good resource for building interface, Therefore, there is no user-friendly interface), which is solved by using $(‘.main’) in index.html to display the interface of the $(‘.main’) element (the background should be the same as the preloaded scene background). To make the scene load too long for a good user experience, and when the scene is finished loading $(‘.main’) can also make a good connection to the preloaded scene.
The specific code is as follows:
var Boot = function(game) {
var baseURI = localStorage.baseURI
this.init = function() {//game.device.desktoptrueAs the PC,falseFor the WAP clientif(! Game. The device. The desktop) {/ / set the game background game. Stage. BackgroundColor ='#282C34'; // Set the pointer object to 1 (null) game.input. MaxPointers = 1; // Scale control, where the canvas is stretched until it fills the parent container (i.e#game-container), do not maintain proportionsgame.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL; / / enabled, shows the canvas (canvas) will be in the parent container horizontal alignment game. Scale. PageAlignHorizontally =true; / / enabled, shows the canvas (canvas) will be in the parent container vertical alignment game. Scale. PageAlignVertically =true; // Force the game to run in only one direction, here the game can only run in portrait mode (true), can no longer run in landscape mode (false) game. Scale. ForceOrientation (false.true); // When forceOrientation is set to run only in portrait mode, Put mobile phone transverse is called enterIncorrectOrientation game. This approach scale. EnterIncorrectOrientation. Add (enterIncorrectOrientation, this); / / when forceOrientation set only longitudinal mode, put mobile phone transverse enterIncorrectOrientation will call this method, To put mobile phone longitudinal is called leaveIncorrectOrientation game. This approach scale. LeaveIncorrectOrientation. Add (leaveIncorrectOrientation, this); }else{
game.scale.pageAlignHorizontally = true
game.scale.pageAlignVertically = true// Prevents the animation from pausing after the browser loses focus, which can be set to if computer performance is consideredfalse
game.stage.disableVisibilityChange = true;
}
}
this.preload = function() {// set images to support cross-domain requests game.load. CrossOrigin =true// Load the resources required by the preload interface, you can see the image and $('.main'The first parameter is the resource id needed to create the Sprite object, and the second parameter is the resource path game.load. Image ('start_bg', baseURI + '/img/bg.png')
}
this.create = function() {// Jump to the next scene game.state.start()'Preload');
}
function enterIncorrectOrientation() {
alert('Please place your phone vertically.');
}
function leaveIncorrectOrientation() {
alert('Phone has been placed vertically'); }}Copy the code
Each line of code above has been commented out, so you can look at it and understand it if you have time, but for now we just need to know that boot.js is just used to set up all of our scenarios and load the resources needed for our second scenario, preload.js.
preload.js
This scene is a pre-loading scene, which will load the resources of all the following scenes. Since there are a lot of resources to load, we need to show our resource loading process in a friendly way in this scene, using the start_bg resource that has been loaded for us in the last scene. And Phaser’s own text object that shows the loading progress.
In preload.js, note that we need to load a frame image.
The first parameter is the resource id needed to create the Sprite object, the second parameter is the path of the image, and the third parameter is the name of the image XML file game.load.atlasxml ('sprites', baseURI + '/img/sprites.png',baseURI + '/img/sprites.xml')Copy the code
We need an overall picture that contains all the actions, as well as a configuration XML file. So the question, why do we need two files, why not just make the frame image into a dynamic figure then show, this question is very simple, first direct a moving figure far is much bigger than a static image (XML file is too small ignored), and we can’t control brake figure in the code switching speed.
Ok, now let’s do our thinking. If we have two images that need to be made into giFs in Phaser, like the following:
Then how do we synthesize them into the overall picture and configuration XML file that we want? That’s when we need software to handle it. Here’s how Shoebox works:
The website address
After downloading and installing, we opened Shoebox and moved each frame of the GIF to Sprite Sheet. Let go of the picture:
Click Save, and you have generated a frame image and an XML file:
The XML file mainly records the location and name information of each action image that we include in the frame image, but of course, this is not our focus.
The specific code is as follows:
var Preload = function(game) {
var baseURI = localStorage.baseURI
var tool = new utils()
var w = null
var h = null
var start_bg = null
var loading = null
this.init = functionGroup =game.add.group() {// get the width of the canvas (w = game.width h = game.height);'.main') element hides $('.main'.hide() // Since start_bg and $('.mian') interface is consistent, the user is not able to see $('.mian'Hide start_bg to show the process // create a Sprite object. The first parameter is the canvas x coordinate (how far from the left edge of the canvas), the second parameter is the canvas y coordinate (how far from the top edge of the canvas), The third parameter is the resource to build the object start_bg = game.add.sprite(0, 0,'start_bg'SetFull (start_bg) // Create a text object with the first two arguments as Sprite and the third argument as text content. Loading =game.add.text(w*.5, h*.5,'0%',
{
fontSize:60,
fill:'#ffffff'}) // Anchor position (relative to itself), the first parameter is how much to move to the left relative to itself (.5 is 50% of its width to move to the left), Set (.5,.5) // Loading the last position is centered relative to the canvas // Loading the tambien animation, from (from what state to the default state), To (from the default state to what state), the first argument used here is from // : a JS object containing the property to be animated, {alpha: 0} said transparency of 0 / / the second parameter: the duration of the animation / / the third argument: animation process function, the default animation at a constant speed for Phaser. Much. Linear None / / the fourth parameter: whether to automatically start / / fifth parameters: The delay before the animation starts, in milliseconds // Sixth argument: the Number of times the animation repeats, if you want the animation to loop forever, set this value to number.max_value // seventh argument: Whether to automatically reverse game.add.tween(loading) from({alpha: 0}, 500, null,true, 0, 0, false)
}
this.preload = function() {
game.load.crossOrigin = trueThe first parameter is the resource id needed to create the Sprite object, the second parameter is the path of the image, and the third parameter is the name of the image XML file game.load.atlasxml ('sprites', baseURI + '/img/sprites.png',baseURI + '/img/sprites.xml')
game.load.image('next', baseURI + '/img/next.png')
game.load.image('img2_1', baseURI + '/img/2_1.jpg')
game.load.image('img2_2', baseURI + '/img/2_2.jpg') / / this method is the file loading process, return progeress is to achieve progress, 0 ~ 100 game. The load. The onFileComplete. Add (function(progeress) {
loading.setText(progeress + The '%'}) // This method is called when all files have finished loading, and we can jump to the next scene when calling this method. The effect is the same as executing game.state.start('State1')
game.load.onLoadComplete.add(function() {
game.state.start('State1')
})
}
this.create = function() {
//game.state.start('State1') }
this.update = function() {}}Copy the code
$(‘.main’).hide(). This is what we imported earlier in jquery.min.js to prove that you can write any jquery code inside a Phaser.
If you have a complete understanding of the above two scenarios (boot.js and preload.js), the following two scenarios (state1.js and state2.js) should be pretty quick.
state1.js
This scenario is mainly used for Phaser giFs, events, and animation groups. If you are careful, you can see that the code used to initialize and build the scene in the CREATE method is written in the preload method. In my experience, as long as a scene does not require preloading resources, the preload method is no different from the CREATE method.
The specific code is as follows:
var State1 = function(game) {
var baseURI = localStorage.baseURI
var tool = new utils()
var w = null
var h = null
var next=null
var sprites=null
var group=null
this.preload = function() {w = game.width h = game.height, Sprites =game.add.sprite(w*.5,h*.6, w*.6, w*.6)'sprites',0)
tool.setSize(sprites,'width',w*.5) sprites.anchor. Set (.5,1) // Add a new animation to the Sprite object, the first argument being the animation name sprites.animations.add('run'The first parameter is the animation name, the second parameter is the playback speed, and the third parameter is whether to loop sprites.animations.play()'run', 4,true) / / to add start_bg animation group group. The add (sprites) next = game. Add the Sprite (8, w *. 5, h *.'next')
tool.setSize(next,'width',w*.3)
next.anchor.set(.5,.5)
game.add.tween(next).to({ width:next.width+20,height:next.height+20 }, 500, Phaser.Easing.Linear.In, true, 0, 1,true) group.add(next) // By default, the gameobject does not handle any events, so we need to make it handle events next-inputenabled =true/ / when the next object click and then let go of the trigger finger next. Events. OnInputUp. Add (function() {// The onComplete method is a callback after the tween animation is completed, so we can make some user-friendly exit animation of the current scene before moving to the next scene. Game.add.tween (group). To ({alpha: 0 }, 500, Phaser.Easing.Linear.In,true, 0, 0, false).onComplete.add(function() {
game.state.start('State2')})})}}Copy the code
state2.js
This scene is just a continuation of the next button click from the previous scene.
var State2 = function(game) {
var w = null
var h = null
var img2_1=null
var img2_2=null
this.preload = function() {
w = game.width
h = game.height
img2_1=game.add.sprite(0,h*.5,'img2_1'Img2_1. Width =w img2_1. Height =h*.5 img2_1. Anchor. Set (0,1) game.add.tween(img2_1).to({y:h}, 2000, Phaser.Easing.Linear.In,true, 500, 1,true)
img2_2=game.add.sprite(0,h*.5,'img2_2')
img2_2.width=w
img2_2.height=h*.5
game.add.tween(img2_2).to({ y:0 }, 2000, Phaser.Easing.Linear.In, true, 500, 1,true)
}
this.create = function() {}}Copy the code
Well, without further ado on state2.js, you already know what kind of animation this scene looks like.
Chicken soup cooked all day
Well, that’s the end of the story. There’s so much more interesting about Phaser to discover. If you want to learn more, you can go to Phaser’s website.
Here special thanks to the great god Li Shichan who took me crazy into the pit, and technical support for this article.
Here I congratulate you all on happy Double 12 and progress in your career!