WeChat mini game and Egret engine development practice

Source: Internet
Author: User
Tags addchild event listener
Preface

This paper introduces and understands the small game and Egret engine according to the author's research and development order, and produces the application initialization program Egret-wechat-start based on Egret engine. Here is the text--

Mini Games Official DocumentsHow to develop and understand small games, start with official documents and official demo.  Provide a link to developers.weixin.qq.com/minigame/dev/, you can quickly browse the official documents and then continue to see the following content.  Here is a simple summary of the document, small games and small programs are similar in many places, are provided with the same set of APIs, such as access to user information, toast, and so on, just a few of the API is different. The mini-game encapsulates the canvas by wx.createCanvas() 创建画布, getContext获取对象后,剩下的就是对原生canvas接口的操作了。  理解到这一点之后,我们就会发现小游戏仅仅是封装了下创建画布的接口,剩下的就是用户需要在画布里用原生canvas绘制了,并没有提供其他方便开发的功能。到此我们再看看开发者工具创建小游戏项目时,初始化的一个飞机游戏的demo。  是如的一个很简单的游戏,说下这个游戏的大致实现逻辑:1. Draw the game area, background picture 2. Create enemy object, user aircraft object, Bullet object 3. Controls 3 objects loading canvas and position changes, controlling background image movement, adding sound effects 4.  Judging bullet collisions, fuselage collisions, and generate corresponding results (enemy aircraft disappear, the game ends) in the game and the user has the interactive operation has the drag airplane and the box button, the overall is a very simple small game, the realization process is not complicated.  The most important animation content in the official demo is in the loop method, using a frame animation (requestanimationframe) to animate the interface. There are two main ways to achieve animation for the game, one of which is RequestanimationframeFrame animation, one is implemented with a timer.  Frame animation is related to the processing speed of the device, the default 1 seconds 60 frames, but in the mobile device even if the very simple animation, the performance of the device may be almost the same frame rate of about 20-30. Because frame animations call n times per second, they may not require a high-frequency function call, and timers generally have more accurate control of time and function calls. For example, if there is a concept of blood bar in this airplane game, the addition and subtraction of the blood bar can be controlled by a separate timer.   A game can be used in both ways, depending on the application scenario to choose a more reasonable way. Now make a game based on a new requirement, then understand the development of the mini-game. now the need to implement a turn-based game, the game also has a lot of pages, the home page contains a lot of buttons and possible pop-up windows, there are various list pages, as well as the most critical battle page. Before implementing the requirements, we need to provide some common basic modules: resource preloading, Interface interceptor, simple routing and so on. Skip these stages, if we get UI design, start to do the homepage, the home has a lot of buttons, we need to give a button to add the binding event, then we need to bind a click event to the Canvas canvas, click on the trigger we get to the current user click Position, and take out a button position wide and calculate the range, Make a decision whether to click on the location in the range, and then trigger the binding method finally.  It seems to be a bit of a hassle, but it can be done and go ahead.  Later need to make a frame on the home page, this time, the B button to the box to bind the point-click event, but also need to use the same method to determine whether to click the B button.  This time the B button of the box just overlaps the a button in a single click, and the callbacks for both A and B are executed. The code is as follows:
Canvas.addeventlistener (' Click ', (event) ={    Get Event object x, y    get buttona:x,y,width,height    determine if click    get Buttonb:x,y,width,height to    determine whether to click})

A popup window above the button click, instead of the box below the button also clicked to, this does not meet the expectations, that to solve this problem, we also need a hierarchy manager, according to the level of judgment who should trigger, who should not trigger. Currently we need to implement two basic functions, the event listener pool and the element object level manager, because events can only be tied to the canvas, and after the canvas event is triggered, an event listener pool is required to traverse the element object in the listener pool and determine who is triggered (the listener also increases or decreases the listener at any time)  , the listener pool gets a set of objects that the Hierarchy Manager determines the topmost element in the set of objects to trigger.  Think of features that seem to be getting more complicated.  Not yet considered perfect, not just the issue of incident handling, there may be other large and small problems.  With canvas native development, the workload can be very large.  So it seems that it is unscientific to make these implementations, and we need to use a three-party engine to develop them. Because the Egret engine was used two years ago, so on the incident monitoring and hierarchy management This thing, I know Egret engine has been realized, except events, graphics, animation and so on the impression of Egrets are provided, if the engine development of small games to realize the cost is greatly reduced.

Egret EngineEgret engine is very powerful and rich in function. Here I first introduce my main use of tools.
    • Egret engine2d
    • Texture merger
    • Egret Extension Library
    • Egret Wing

Egret engine2d

Major core APIs in development

Texture merger

Texture merger can flatten scattered textures into full images, and also parse SWF, GIF animations, make Egret bitmap text, and export a configuration file that can be used for Egret. I mainly use the sprite diagram function, the picture is assembled to a picture, and will also export a JSON sprite diagram in the picture location and other configuration information

Egret Extension Library

The extension library provides a more advanced API on top of the core engine features, and the extension library is configured in the engine configuration file to directly load the methods and objects into the Egret global object, and currently I use the main extension libraries:

    1. RES: Resource Management Library
    2. Eui:eui is a set of UI extensions based on the Egret core display list, which encapsulates a large number of common UI components to meet most of the interactive interface requirements, and even more complex component requirements can be combined or scaled based on EUI existing components to quickly implement requirements.
    3. Game: This library does not seem to have any specific definition, I mainly use: ScrollView scrolling view. To handle pages that need scrolling
    4. Tween: Slow Motion Library, similar to Greensock library

Egret WingThe code editor developed by Egrets, like other editors, recommends using it. Egret LauncherOf course, you also need to install a Egret launcher to manage the engine, tools, and project packaging, and the mini-game needs to be packaged before it can be used in developer tools.

Start Egret Development

You can quickly browse through the official tutorials to get a better understanding of the http://developer.egret.com/cn/github/egret-docs/Engine2D/getStarted/helloWorld/index.html.  The article is not a tutorial, so I will omit those on the Egret official website of the tutorial. Now we use Egret launcher to create an initialization project, after the initialization of the file structure such as, I expanded the resource and src folders, because we need to operate mainly these two folders, Resource folder is mainly to store static resources, our code is in src , egrets use typescript.

In the wing tool, we can start debugging right away and preview the effect in the browser or its own container. Main.ts is the startup file, andmain first uses await to preload the picture resource defined in resource , so the preview will appear after the start loading effect,loading is written in src loadingui.ts, after the picture is loaded,main directly creates 2 of the page, and adds a button,  A pop-up window will appear when clicked. Effects such as.

At this point, the Init demo has already told us how to draw the image and bind the event, for example, I have only intercepted the click button Code, the image drawing first need to create a corresponding Egret or eui object, such as Eui. Button, Egret. TextField, Egret.  Bitmap and so on, then set the appropriate properties for the object, such as label, x y coordinate,width, height , etc. Then use main 's addChild to load into the canvas (the following is the main object, andmain inherits from the Eui.  Uilayer). The code in the demo is loaded into the loading, using this.stage.addChild, directly addChild or using stage.addchild  Can be loaded into the canvas. The AddEventListener method of the Egret package and the native JS monitoring method are the same way of use.

Demo code to summarize here, we can use addChild in the main entry object to load a view object into the canvas, such as text, buttons and so on. We can also addChild a View container A in main , view container A can also add text buttons and so on, then we addChild view container b again in view container A, so that it forms a hierarchy of nesting main->a->b, if you think of it as a DOM element is Div.main->div. A->div. B 's relationship, let's compare it with the code:

class Main extends Eui. Uilayer {protected Createchildren ():void{Let A=NewEgret.        Displayobjectcontainer ();  This. AddChild (A); Let Texta=NewEgret.        TextField (); Texta.text= ' Text A Description ';        A.addchild (texta); Let B=NewEgret.        Displayobjectcontainer ();                A.addchild (B); Let Buttonb=NewEui.        Button (); Buttonb.label= ' button B ';    B.addchild (BUTTONB); }}

Corresponding

<Divclass= "Main">    <Divclass= "A">        <span>Text A Description</span>        <Divclass= "B">            <Buttonvalue= "button B"></Button>        </Div>    </Div></Div>

Based on the above code understanding and what we need to do (to implement a turn-based game, this game also has a lot of pages, the home page contains a lot of buttons and possible pop-up windows, there are various list pages, as well as the most critical combat page).  I write a initelement method in main , create a grass-roots container, code such as,AddChild by default in order to determine the upper and lower relations, first load the next layer. First, the lowest level creates a background layer, followed by ScrollView and basecontent, and the page container loads into them, and if the page needs scrolling, it loads the page view object into the SV, without scrolling to load into Basecontent ,layer and loading are in the upper position.

When the base container is ready, we can create a home page. I will create 3 files:base.ts,index_ui.ts,index.ts。IndexInheritedindex_ui,index_uiInheritedBase。 All the_uiWill InheritBase,BaseGeneric methods and properties are defined. Because a page to the last possible code size will be relatively large, or even messy, so that a page split intopageAndpage_ui,_uiWrite the view-related code,pageCalled in_uimethods, processing requests, and writing logic to achieve the effect of view and logical separation. When the home page is written, you need to create a simple route, using the method provided by the route toIndexAdd toSVThe container. I wrote the route directly to the in main,ChangepageIs the method of page switching, the code is roughly as follows:

Through remove and _ui page, below is INDEX_UI Part of the code, el_layout pre-defines and manages the layout information of page elements in advance.   Put index the element that the logical page needs to manipulate is referenced to $el Easy to invoke and manipulate in the object.   Unify the data information in $data .   Before creating a page view element, you need to pass the y-coordinate of the first element to $firstEleY This is for the back pagecontentcenter method to get the exact height of the page content, to perform after all page element creation is complete, pagecontentcenter is centered vertically based on the height of the current page and the height of the current device.

Class INDEX_UI extends Base {public    el_layout = {        indexbg: {x:0, y:0, w:750, h:1665},        Gold: {x:300, y:100, W: H:39}    };    Public constructor () {        super ();        This. Res_index = res.getres (' index ');        This. Res_common = res.getres (' common ');    }    public res_index;    public Res_common;    Public $el = {        Gold:object (Egret. TextField)    } public    $data = {        Gold: ' 0 '    } public    Async CreateView () {

Background
Let RES_BG = New Egret. Bitmap (Res.getres (' indexbg '));

$util. setlayout (RES_BG, this.el_layout[' indexbg ');

      Res_bg.fillmode = Egret. Bitmapfillmode.repeat;

this. $main. Pagebg.addchild (RES_BG);

        The top element must pass the value of this        . $firstEleY = This.el_layout.gold.y;        This.pagecontentcenter (TRUE);//center by Content calculation processing    }}

A simple development package core code has been set up, and then we need to encapsulate some other tool classes, such as: Configuration files ($config), encapsulation Interceptors ($API), Filters ($filter), tool functions ($util), API Encapsulation (WX). platform.ts is an auto-generated file for egrets, According to its rules to write a wx.ts file, due to different platform interface forms are different, egrets recommend developers in this way to encapsulate the platform logic to ensure the stability of the overall structure, egrets recommend the developer to encapsulate all the interface as a Promise-based asynchronous form.

and SRC sibling also has a texture folder, inside is Texturemeger use sprite diagram of related files, placed in the warehouse is convenient later management.

Simple initialization demo, I have updated to GitHub on Github.com/zimv/egret-wechat-start.  Egret-resource is the source code,egret-resource_wxgame is the package of egrets after the folder, it runs in the developer tool.  Egret-resource_wxgame should be ignored in the ignore, here is not ignored is convenient to download the source of friends directly in the developer tool run demo. The current program uses the Egret engine version 5.2.5.

You can write a few pages in the demo to see the effect:

Pits

And stepping on a lot of pits, the following record:

    • In the public number backstage to set the service class into a game class, input AppID will automatically open the Developer tool game development interface
    • Small game custom font support is poor
    • Some features and APIs need to register a small program to use, such as the forwarding function, currently registered a personal mini-game for early development
    • Using the wing tool to edit the code, compile the debugging, the compiled code will be stored in the Bin-debug folder, I use the Mac, the Project menu has three options to compile, debug and clean. I added a xx file, but in the debugging time has been error, check browser source There is no new files, Bin-debug also did not, got a long time, always thought it was their own code is wrong, and finally realized that may be the compiler has a problem, this time I clicked the cleanup button, The new files appear in the Bin-debug. Should be a bug, pay more attention to check the Bin-debug files are updated
    • Res.getresbyurl is a network asynchronous load, need to advance addchild to ensure that the hierarchy is normal, the request is completed and then modify the texture property of the object, you can also specify the hierarchy through the Addchildat method.
    • TextField font size Less than 10 affects layout, text is wrapped depending on the height of the element set
    • WebGL mode failed to load network URL picture
    • ScrollView has a Addchild method, but the code in the method is a direct throw error, indicating that the interface cannot be used. Its child elements bind Touchstart move and other events will expire, so now add a basecontent, switch the parent container as required
    • Measuredheight this measurement interface only measures the actual height of the top and bottom elements, so the first element if the Y value is greater than 0 pay attention to configuring the $firsteley
    • All images are compressed with tools, which reduces the size of the upload code and increases the speed of resource loading.

Knot

When all this is ready, the rest is physical and, of course, the game's most important core gameplay, animations, and interactive effects, These may be the most difficult part of a game to achieve. Warehouse Address:github.com/zimv/egret-wechat-start .

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.