Phaser is an easy-to-use and powerful html5 game framework that allows you to easily develop an html5 game. In this article, I will teach you how to use Phaser to create a very popular game: Flappy Bird. I hope you can make your own html5 game after reading it. You can click here to try out the game that I have already prepared and feel the effect of the Phaser game. The complete game code has been put on github. Supported browsers: IE9 +, Firefox, Chrome, Opera, Safari, and mobile terminals support html5 browsers. Google browsers are recommended because of their best performance.
The source code of phaser. js can be downloaded through its hosting on github. Click here to download the image sound and other materials required for the game. Phaser is very simple to use. You only need to introduce its main file, specify an element on the page to place the canvas, and instantiate a Game object.
<! DOCTYPE html>
Let's take a look at the parameters of the Phaser. Game function:
Phaser.Game(width, height, renderer, parent, state, transparent, antialias, physicsConfig)
Width: the width of the game, that is, the width of the canvas used to render the game. Unit: px.
Height: the height of the game, that is, the height of the canvas used to render the game. Unit: px
Renderer: Which rendering method is used, Phaser. CANVAS is the html5 CANVAS, Phaser. WEBGL uses WebGL for rendering with better performance, Phaser. AUTO is automatic detection. If the browser supports WebGL, WebGL is used; otherwise, Canvas is used.
Parent: the parent element used to place the canvas element. It can be an element id or dom element. phaser automatically creates a canvas and inserts it into the canvas Element.
State: state can be understood as a scenario. Specifying state here means that the game will load the scenario first, but the state can not be specified here. In the subsequent code, the state will be loaded first. I will provide a detailed description of the state later.
Transparent: whether to use a transparent canvas background
Antialias: whether to enable anti-aliasing
PhysicsConfig: Game physical system configuration parameters
All the above parameters are optional. For more information about their default values, see here. Generally, we only need to specify the four to five parameters above.
After the Game object is instantiated, the next step is to create various scenarios that the Game will use, that is, the state mentioned above. How can we create a state? State can be a js custom object or a function. As long as they exist in any of the three methods preload, create, and update, it is a legal state.
// State can be a custom object var state1 = {preload: function () {}, create: function () {}, update: function () {}} // state can also be a constructor var state2 = function () {this. preload = function () {}; this. create = function () {}; this. update = function () {};}// as long as one of the three methods preload, create, and update exists, var state3 = function () {this. update = function () {};}// of course, other attributes or methods such as var state4 = function () {this. create = function () {}; this. aaa = function () {}; // other methods this. bbb = 'hello'; // other attributes}
The preload method is used to load resources and will be executed first. The create method is used for initialization and build scenarios. It will not be executed until all resources loaded in the preload are loaded. The last update method is to update the function, which is executed at every frame of the game to create a dynamic game.
In this game, we will use four states. We can use the game. state. add () method to add state to the game, and then use game. state. the start () method to call the state. For more information, see the state documentation.
Var game = new Phaser. game (288,505, Phaser. AUTO, 'game'); game. states ={}; // create an object to store the stategame. state. boot = function (){...} // boot scenario, used to prepare the game before the game starts. state. prelaod = function (){...} // prelaod scenario, used to display the resource loading progress game. state. menu = function (){...} // menu scenario, game menu. state. play = function (){...} // play scene, official game part // Add the defined scene to the game. state. add ('boot', game. states. boot); game. state. add ('preload', game. states. preload); game. state. add ('menu ', game. states. menu); game. state. add ('play', game. states. play); // call the boot scenario to start the game. state. start ('boot ');
Create a resource loading progress bar
Resources such as images and sounds used by the game need to be loaded in advance. Sometimes, if there are many resources, it is necessary to create a page for loading resources to improve user patience. Here we use a state to implement it and name it preload.
Because the resource loading progress bar requires a background image of the progress bar, we need another basic state before creating this state to load the progress bar image. we name it boot.
Game. states. boot = function () {this. preload = function () {game. load. image ('loading', 'Assets/preloader.gif '); // loads progress bar image resources}; this. create = function () {game. state. start ('preload'); // call the preload scenario after loading is complete };}
In Phaser, resource loading is done through the method of Phaser. Loader object. The load attribute of the game instance is the Loader object of the current game. Here we are game. load. There are many methods for Loader objects. Different methods can load different resources. For example, we use the game. load. image () method to load images. For a list of specific methods, see the documentation.
In the preload scenario, we need to load all the resources used after the game, and then display a loading progress bar for users. The Loader object provides a setPreloadSprite method. If you specify a sprite object to this method, the width or height of the sprite object will be automatically adjusted based on the percentage currently loaded, achieve a dynamic progress bar.
Game. states. preload = function () {this. preload = function () {var preloadSprite = game. add. sprite (50, game. height/2, 'loading'); // create a sprite game that displays the loading progress. load. setPreloadSprite (preloadSprite); // use the setPreloadSprite method to achieve the dynamic progress bar effect. // The following is the resource game to be loaded. load. image ('background', 'Assets/background.png '); // game background image game. load. image ('ground ', 'Assets/ground.png'); // ground game. load. image ('title', 'Assets/title.png '); // game title. load. spritesheet ('bird ', 'Assets/bird.png', 3); // bird game. load. image ('btn ', 'Assets/start-button.png'); // button game. load. spritesheet ('pipe', 'Assets/pipes.png ', 54,320, 2); // MPs queue game. load. bitmapFont ('Flappy _ font', 'Assets/fonts/flappyfont/flappyfont.png ', 'Assets/fonts/flappyfont. fnt '); // the font of the score displayed in game. load. audio ('fly _ sound', 'Assets/flap.wav '); // The Flying sound game. load. audio ('score _ sound', 'Assets/score.wav '); // the score of the audio game. load. audio ('Hit _ pipe_sound ', 'Assets/pipe-hit.wav'); // The Sound Effects of the hitting pipeline game. load. audio ('Hit _ ground_sound ', 'Assets/ouch.wav'); // hit the ground sound game. load. image ('ready _ text', 'sets/get-ready.png '); // get ready picture game. load. image ('play _ tip ', 'Assets/instructions.png'); // The gameplay prompts the image game. load. image ('game _ over', 'Assets/gameover.png '); // gameover image game. load. image ('score _ board', 'Assets/scoreboard.png '); // score board} this. create = function () {game. state. start ('menu '); // when all the above resources are loaded, you can enter the menu scenario of the menu game }}
The Sprite object, also known as the genie in game development, is mentioned above. In Phaser, the sprite object is also one of the most used and important objects in game production. We can use an image to create a sprite, and then use the many attributes and methods provided by Phaser to operate on it. We used game. add. sprite () to create a sprite, and it will be automatically added to the current game after the creation, game. add represents Phaser. gameObjectFactory object, which provides a series of shortcuts to facilitate the creation of various game components. The resource loading progress page we created here is very simple, which is probably like the following:
Game. states. menu = function () {this. create = function () {var bg = game. add. tileSprite (0, 0, game. width, game. height, 'background'); // The tileSprite var ground = game. add. tileSprite (0, game. height-112, game. width, 112, 'top '). autoScroll (-, 0); // use it as the tileSprite bg on the ground. autoScroll (-10, 0); // set the background to ground. autoScroll (-, 0); // Let the ground move }}
Then let's make the game title. The game title flappy bird is an image, and then the bird is a sprite, And we perform an animation on the sprite, make its wings seem to be moving. What I want to talk about is how to implement animation on a sprite object. First, when loading a bird image, we load a bird image, which is spritesheet (key, url, frameWidth, frameHeight, frameMax, margin, spacing)
Key: Name specified for this image. It will be used later when you create objects such as sprite.
Url: Image address
FrameWidth: the width of each frame in the image.
FrameHeight: the height of each frame in the image.
FrameMax: Maximum number of frames
Margin: the margin of each frame
Spacing: The interval between frames.
In the above picture of the bird, the width and height of each bird are 34px and 24px, so the frameWidth should be 34 and the frameHeight is 24. Then we have three frames in this animation, and the frameMax is 3, there is no gap between the frame and the frame, and the margin and spacing are both 0. In fact, the spritesheet method allows us to load an image and divide the frames on the image. In the future, sprite of the image can use these frames to play the animation. To implement an animation on sprite, we must first define an animation, which is composed of frames. The sprite object has an animations attribute, which represents the animation management object of Phaser: AnimationManager. The object has an add method for adding animations and a play method for playing animations, for specific parameters, see the documentation.
Next we will talk about a very important object: Phaser. Group, that is, Group. A group is equivalent to a parent container. We can put many objects into a group, and then perform batch or whole operations on these objects using the methods provided by the group. For example, to allow objects in a group to be displaced, you only need to perform group displacement. For example, you need to perform Collision Detection on all objects in the group, you only need to perform Collision Detection on the objects in this group. The title of the game we want to create is composed of a text image and a bird. We put these two items in a group and then perform the overall operation.
Game. states. menu = function () {this. create = function (){...... var titleGroup = game. add. group (); // create the titleGroup that stores the title. create (, 'title'); // create a title image using the create method of the group and add it to the group var bird = titleGroup. create (190, 10, 'bird '); // create a bird object and add it to the group. animations. add ('fly '); // add an animation bird to the bird. animations. play ('fly ', 12, true); // play the animation titleGroup. x = 35; // adjust the horizontal position of the group to titleGroup. y = 100; // adjust the vertical position of the group game. add. tween (titleGroup ). to ({y: 120}, 1000, null, true, 0, Number. MAX_VALUE, true); // Add a tween animation to this group to keep it moving up and down }}
The Tween object in the above code is used to implement the animation of the compensation room. Get a tween object through the Tween method of game. add. The parameter of this method is the object that requires animation. Then we can use the to method of the Tween object to implement the animation of the population.
to(properties, duration, ease, autoStart, delay, repeat, yoyo)
Properties: A js object that contains the attributes to be animated, as shown in {y: 120} in the code above}
Duration: the animation duration in milliseconds.
Slow: The easing function. The default value is constant speed animation.
AutoStart: whether to start automatically
Delay: the delay time before the animation starts, in milliseconds.
Repeat: the Number of animation repetitions. If you need to keep the animation repeating forever, set this value to Number. MAX_VALUE.
Yoyo: if this value is true, the animation will automatically reverse
Add a button to start the game. Phaser provides a Button object so that we can easily implement a Button.
Game. states. menu = function () {this. create = function (){...... var btn = game. add. button (game. width/2, game. height/2, 'btn ', function () {// Add a button game. state. start ('play'); // jump to play scene when you click the button}); btn. anchor. setTo (0.5, 0.5); // set the center of the button }}
In Phaser, many objects have an anchor attribute, which indicates the center point of the object. The axis of position translation and rotation of the object is referred to by this center point. Therefore, in the code above, we want to center the buttons horizontally and vertically. Apart from setting the x and y attributes of the buttons to the width and height of the game, set the center of the button to the center of the button.
Finally, we combine all the code to get the final code of the state menu. This state only requires a create method:
Game. states. menu = function () {this. create = function () {game. add. tileSprite (0, 0, game. width, game. height, 'background '). autoScroll (-10, 0); // background image game. add. tileSprite (0, game. height-112, game. width, 112, 'top '). autoScroll (-100,0); // floor var titleGroup = game. add. group (); // create the titleGroup that stores the title. create (0, 0, 'title'); // title var bird = titleGroup. create (190, 10, 'bird '); // Add the bird to the group. animations. add ('fly '); // add an animated bird. animations. play ('fly ', 12, true); // play the animation titleGroup. x = 35; titleGroup. y = 100; game. add. tween (titleGroup ). to ({y: 120}, 1000, null, true, 0, Number. MAX_VALUE, true); // The title compensation animation var btn = game. add. button (game. width/2, game. height/2, 'btn ', function () {// button game. state. start ('play') ;}); btn. anchor. setTo (0.5, 0.5 );}}
The second part of the Tutorial:
Use Phaser to create an html5 game-flappy bird (2)