This article is published by the Cloud + community

Using a simple game development example, from shallow to deep, introduced how to use Laya engine to develop micro channel games.

Author: Ma Xiaodong, Tencent front-end senior engineer.

It has been nearly a year since the launch of Micro-channel games. In THE game operation activities of IEG, there are more and more activities operated by micro-games, such as game reservation, pre-trial and so on, which have received very good results.

Among the game engines that support micro-games on wechat, Cocos, Egret and Laya all provide a lot of powerful support for the development of micro-games. Some time ago just took time to study the content of this piece, now make a summary, for how to use Laya engine to develop micro channel games to give you a brief introduction. Because the time is limited, the research is not in-depth, if there is a master passing by, forget to give advice.

What kind of game? Pubg is very popular. How about we do a jedi death wish? The planning is also very simple, and contrary to pubG, the main character is not the parachuting player, but the ground gunner, the cannon to parachute paratroopers with the cannon to destroy one by one.

Awesome planning, let’s get down to business, see how to achieve it!

1. What if you don’t use an engine?

1.1 Canvas

Wechat mini-game provides canvas, the core component of the game. Canvas can be used to draw text, graphics, images and so on. But before we talk about wechat games, we have to talk about H5 first. In the ERA of H5, it is very easy to acquire canvas objects, as shown below:

var canvas=document.getElementById("myCanvas");
var ctx=canvas.getContext("2d");
Copy the code

Some commonly used apis:

ctx.drawImage(img,sx,sy,swidth,sheight,x,y,width,height); // Draw a picture

ctx.fillText(text,x,y,maxWidth); // Draw text

ctx.rect(x,y,width,height); // Draw a rectangle

ctx.clearRect(x,y,width,height);// Clear the pixels in the rectangle

ctx.scale(scalewidth,scaleheight);/ / zoom

ctx.rotate(angle);// Rotate the Angle.Copy the code

Wechat mini game also provides canvas object, but the access interface is changed:

wx.createCanvas()
Copy the code

Canvas APIS in other H5 environments are also available in wechat environment.

1.2 Principle of animation

Canvas is just a 2D Canvas. To make a game, animation is necessary, right? How do you make an image move? See the picture below:

Well, animation is just a cycle of drawing pictures, erasing, drawing pictures, erasing. To the naked eye, it’s moving.

In the old days of celluloid, the movie we saw was a series of frames that were projected onto the big screen and became the movie we saw.

1.3 Animation performance optimization

However, animation is very framerate, generally if can reach 60 frames per second, it is very smooth animation effect like film. Calculation formula: 1000ms/60fps=16.67ms, which requires that the business logic calculation in each animation should be completed in 16.6ms, without affecting the display of the next frame, otherwise it will be stuck, which will be said that the game is good card, good performance.

Now that we know the principle, how do we do performance optimization?

  • Canvas layer In some games, the background is unchanged. In order to improve performance, the game background can be separated from a separate Canvas. In this way, when the picture changes, it is not necessary to redraw the whole background, but only the changed part can be drawn.
  • Reducing API calls Each CTX API call consumes performance, so minimize the number of API calls per frame, depending on business requirements.
  • Image pre-cropping image cropping process, also has a performance cost, we can crop the image in advance, when drawing, directly out of memory, rather than need to re-cropping every time.
  • Off-screen drawing directly operates on the canvas of the upper screen, and the performance is very poor, especially when there are many single-frame drawing operations, the performance degradation is more obvious. At this time, we can pre-create an off-screen canvas, complete all the actions to be drawn for this frame on this canvas in advance, and finally draw the off-screen canvas to the upper canvas once.
  • Avoid blocking since we need 16.67ms to complete a frame drawing, what if the logical operation time in this frame exceeds 16ms? It’s bound to get stuck. We can use techniques such as WebWorker to execute time-consuming logical computations in another thread, or to take tasks apart to reduce the elapsed time per frame.

Of course, there are many other skills and means to improve the performance of canvas. In this case, if we directly use Canvas to develop a game, we will also face problems such as collision algorithm and physical system. So, if you only use canvas to develop your game, it’s like you’re playing Chicken with a pan. How can you compete with people?

So, we need to arm ourselves with a 98K, which is game engine development.

2. Why Laya?

At present, there are Cocos, Egret and Laya engines that support wechat mini-games. Let’s first look at the function comparison of the three:

In terms of various supports, Laya has the best support at present, and according to the propaganda of Laya side, its performance is also the highest. (As for the performance issue, due to a large number of external water forces, we will not comment on it until we have done a detailed test.)

Internally, there are all three engine game implementations, and here are the percentages of publicly available engines as of May:

In fact, all three engines provide good support. Generally speaking, Cocos is the best choice for those who have previously implemented APP games and want to port them to wechat mini games. If you want to develop a mini game from scratch, you should choose one in Egret and Laya.

3. Build a Laya environment

So much of this is just foreplay, just to give you an idea of what the game is about, and from this section we’ll get down to business.

Go to www.layabox.com/ to download the latest version and install it. There are currently 1.x and 2.0 versions. (This article uses version 1.7.20 as an example.)

We can then create a new game project, and we can now choose to create a UI sample project

[Create a New project]

3.1 Code Mode

Of course, it’s where you write your code. It feels like this editor is based on VSCode. Even the Code symbol at the top is still there. Because of this, TypeScript is well supported.

[Code pattern layout]

Why use TypeScript? We won’t go into the details here, but TypeScript is a superset of Javascript, because the extra “Type” means it supports strong typing, and because static typing lets the editor tell you when you’re writing code, it’s better suited for more complex applications like games. Of course, TypeScript will eventually be compiled into normal Javascript execution, just like ES6. But when it comes to managing code during development, you can handle large projects.

3.2 Design Mode

This is where the UI is designed, and you can drag and drop the game page. Laya provides a lot of components, if you need to use, of course, you can not use his components, their own custom components.

[Design Mode Layout]

4. Laya的HelloWorld

It is said that as a programmer, after buying the four treasures of the study, the first line of writing must be “Hello World”. (The first line I wrote was also “Hello World” when I took the LAMY pen for the 20th anniversary just issued by the company.)

4.1 Game initialization

4.4.1. GameMain. Ts

Delete the default file “layauisample. ts” and create a new file GameMain

import WebGL = Laya.WebGL;
class GameMain  {    
    constructor() {
         //TS or JS version initializes the adaptation of wechat mini-games
        Laya.MiniAdpter.init(true.false);        
         // Initialize the layout size
        Laya.init(375.667, WebGL);
                 
         // Set the layout modeLaya.stage.scaleMode = Laya.Stage.SCALE_SHOWALL; Laya.stage.screenMode = Laya.Stage.SCREEN_VERTICAL; Laya.stage.alignV = Laya.Stage.ALIGN_CENTER; Laya.stage.alignH = Laya.Stage.ALIGN_CENTER; }}new GameMain();
Copy the code

Laya.miniadpter.init () is an adaptation provided by Laya for small games. In the environment of small programs and small games, there is no Bom and DomAPI, for example, there is no Window document. Therefore, such an adapter is needed to be compatible with the development mode of small games.

4.1.2. Bin/index. HTML

Modify the index.html in the bin directory and delete the reference to layauisample. ts as follows:

<! Start class add here --><! --jsfile--Main-->
<script src="js/GameMain.js"></script>
<! --jsfile--Main-->
Copy the code

In index.html, Laya provides many libraries, which will eventually be packaged into a single code.js. Because of the volume limitation of wechat mini game, we don’t need to load all the libraries in, just select the libraries we need, and delete the ones we don’t need.

4.1.3. run

Next, click Run and the emulator screen will appear.

[Running the simulator]

Forget the black blob, now we’re going to add “Hello World”.

4.2 Drawing Text

2. Laya. Text

Var TXT: laya.text = new laya.text ();

import WebGL = Laya.WebGL;
class GameMain  {
    constructor() {         
    //TS or JS version initializes the adaptation of wechat mini-games
        Laya.MiniAdpter.init(true.false);        
        
        
        // Initialize the layout size
        Laya.init(375.667, WebGL);        

        // Set the layout mode
        Laya.stage.scaleMode = Laya.Stage.SCALE_SHOWALL;
        Laya.stage.screenMode = Laya.Stage.SCREEN_VERTICAL;
        Laya.stage.alignV = Laya.Stage.ALIGN_CENTER;
        Laya.stage.alignH = Laya.Stage.ALIGN_CENTER;

        // Create a Text object
        var txt:Laya.Text = new Laya.Text();        
 
        // Assign a value to the property of Text
        txt.text = "Hello World";// Set the text content
        txt.color = "#ffffff"; // Set the color
        txt.fontSize=20; // Set the font size
        txt.pos(100.200); // Set the position

        // Add the Text object to the stageLaya.stage.addChild(txt); }}new GameMain();
Copy the code

In the code above, we add the Text object to the Stage and hit Run

Uh-oh, the legendary HelloWorld has finally appeared

4.3 Drawing Pictures

4.3.1 loadImage

Laya’s Sprite provides a very simple loadImage method that loads images instantly and loads them onto the stage.

// Set the stage background color
 Laya.stage.bgColor="#1e83e8";
// Create an img Sprite
var img:Laya.Sprite = new Laya.Sprite();
// load the display image at 100,50 and set the width and height to 130*108
img.loadImage("demo/paratrooper.jpg".100.50.130.108);
// Add the image to the stage
Laya.stage.addChild(img);
Copy the code

Preview below, isn’t it easy?

But this method, in fact, is not practical, in real projects, there will be a lot of pictures, we do not load one picture after another, but pre-load good, and then show the picture. The progress bar, often seen on the game’s main screen, is actually loading resources.

4.3.2 Preloading Resources

Laya provides a resource loader, Laya. Loader, to solve the loading problem. We put the above code to modify the realization of the first load of the picture, and then draw the picture.

private imgPath1:string="demo/paratrooper.jpg";
private imgPath2:string="demo/shell.jpg";
constructor() {
        / /... Omit N lines of code
       this.renderImage();
        / /... Omit N lines of code

}

renderImage():void{    
    // Define a collection of image paths
    var resArray=[
            {url:this.imgPath1,type:Laya.Loader.IMAGE},
            {url:this.imgPath2,type:Laya.Loader.IMAGE}
        ]

// Use the loader to load the image path
Laya.loader.load(resArray,Laya.Handler.create(this.this.onLoadComplete),Laya.Handler.create(this.this.onLoadProgress))
}
// After loading, draw the image onto the canvas
onLoadComplete():void{
     console.log("Load complete"); 

     var img1:Laya.Sprite = new Laya.Sprite();
     img1.graphics.drawTexture(Laya.loader.getRes(this.imgPath1),100.50.100.100);
     Laya.stage.addChild(img1);

     var img2:Laya.Sprite = new Laya.Sprite();
     img2.graphics.drawTexture(Laya.loader.getRes(this.imgPath2),100.300.100.100);
     Laya.stage.addChild(img2);
 }
// Here you can get the loading progress, you can make progress bar later
onLoadProgress(percent:number):void{
        console.log("percent->"+percent);
}
Copy the code

4.3.3 atlas

Just preloading pictures is not enough, the actual scene because there are a lot of small pictures, so we can put these small pictures together a composite atlas, which is similar to the front-end in the performance optimization sometimes used CSS Sprite Sprite map, so made into an atlas, not only loading performance is higher, but also easier to make frame animation.

Atlas loading looks like this:

var resArray=[
            {url:"res/atlas/demo.atlas".type:Laya.Loader.ATLAS},
        ]
 Laya.loader.load(resArray,Laya.Handler.create(this.this.onLoadComplete),Laya.Handler.create(this.this.onLoadProgress))
Copy the code

Instead of laya.loader.IMAGE, type becomes laya.loader.ATLAS.

So how do you make an atlas? Also, a lot of game interface, really rely on manual picture by picture display? Of course not! Because it’s time to look at the UI editor.

5. UI editor

The UI editor, of course, is used to edit the UI, and most client development environments have similar UI editors. Click on the left

Icon, enter UI editor mode, as shown below:

Specific UI editor function introduction, it is recommended to see the official document, here is not redundant.

5.1 create the UI

Since we’re creating the default UI project, we have a TestPage. UI in the UI editor, so we can leave it alone and create our own UI. Go to File -> New File

Enter the new page window, the page types are View and Dialog, because here we are doing the whole page, so select View. If you are interested in the source code, Dialog is also implemented based on a View, but with some additional Dialog features.

If you have logic code to write behind the view, it is recommended to check “Create Logic Class”. This will automatically create a GAMepage.ts corresponding to the UI in the View directory

[New page UI]

5.2 Importing Resources

In assets, create a new demo resource directory, throw in all the images you need, and look for the refresh button at the bottom of the resources panel in the UI editor

, must remember to click “Refresh” after the new resource picture, otherwise the content of the resource panel will not automatically refresh.

As long as the image is under the demo file, it will be automatically packaged into an atlas, the path is res/atlas/demo.atlas. I wonder if you have noticed that in the picture above, some resources show “no packing”. What is the reason?

Click “File -” project Settings. We see that the atlas limits the maximum width and height of individual images that can be entered into the atlas, and the maximum width and height of the final atlas. The default criteria can be modified. Images that exceed the gallery standard are not packaged into the gallery and need to be loaded manually.

[Please fill in the picture description here]

5.3 the editor UI

Edit page function, can use PPT, should be able to use, drag a picture who can’t? Drag the image from Explorer directly into the scene editor on the right. This time we dragged a background of blue sky and white clouds, and put a cannon at the bottom, which looked a bit interesting.

There is a row of ICONS at the top to help align images, providing top alignment, bottom alignment, left alignment, right alignment, center alignment, etc. This is handy if there are many images.

The property bar on the right is more commonly used. Var here, you can give the image component that you drag in a variable name, and that variable name will eventually be used in the logic class that was automatically generated earlier. We’ll give the cannon a variable called pao, which we’ll use later; X,y,width,height here, that’s the coordinates and the width and height, so I don’t need to say more, right?

5.4 export UI

Once the UI is done, the important thing to do is never forget to export it. A lot of beginners forget this. Export UI, will regenerate the atlas and UI-related Settings.

Once exported, let’s look at the laya/ Pages/gamepage.ui file. Regardless of the details, it contains the response configuration file that was automatically generated when we dragged the image.

5.5 use the UI

Now we want to display the GamePage we just edited, so go back and modify gamemain.ts again

class GameMain  {

    // Define the static variable gamePageView
    public static gamePageView:view.GamePage;
    
    constructor() {
       / /...
       this.renderImage();
      / /...
    }

    renderImage():void{ 
        // Resource loading
        var resArray=[
            {url:"res/atlas/demo.atlas".type:Laya.Loader.ATLAS},
        ]
        Laya.loader.load(resArray,Laya.Handler.create(this.this.onLoadComplete),Laya.Handler.create(this.this.onLoadProgress))

    }

    onLoadComplete():void{
         // Initialize the view
         GameMain.gamePageView = new view.GamePage();         
         // Add to the stageLaya.stage.addChild(GameMain.gamePageView); }}new GameMain();
Copy the code

Run it. The main screen, the background, and the cannon are all set up. A good start is half the battle.

Next, according to the original awesome plan, we want to make paratroopers fall from the sky just like PUBGM. How to achieve this? Move on to the animation!

Keep an eye on the Cloud + community for updates in the next post