Building CocosCreator component library

  cocos, Games, html5

图片描述

In the recent development of HTML5 games using CocosCreator (hereinafter referred to as CC), it was found that many games of the company have the same elements, such as countdown bar, settlement page, etc. In the early development, we didn’t find a way to reuse, we could only write from scratch in different game projects. With more and more demands, it is definitely not a good way to build wheels repeatedly. So for CC project, can these reusable game elements be packaged and separated as components? After some exploration, a solution was finally found.

What are CC components

Take the “Taigu Daren” small game on hand Q as an example. Its countdown bar and settlement page also exist in other small games, only in appearance, but the logic processing is the same. The countdown bar and the settlement page here can be understood as components.

clipboard.png
clipboard.png

The logic of the two components is as follows:

  • The countdown bar can set the game time, and the filling length of the countdown bar decreases continuously during the game time. The remaining time will be displayed on the right side of the countdown bar; The callback will be executed after the countdown.
  • The settlement page can set grade scores, and stars can be obtained when reaching or exceeding specific grade scores; Stars will be displayed according to animation logic. The score will be settled from 0 below; After the settlement is completed, a callback will be executed.

It is not difficult to understand through this example that a so-called CC component is just oneGame node containing logic, pictures, animation, audio and other different resources. In CC, a node looks like this:

clipboard.png

As you can see, its structure is defined on the left side of the editor, with its concrete embodiment in the middle and its related properties on the right.

If I want to reuse this defined node in other projects, what should I do?

Into prefabricated resources

In CC,Prefabricated resourcesIt is a very important part and can be understood as a template for nodes. If you want to abstract a completed node into a component, turning it into a prefabricated resource is the most appropriate method.

When we have defined a node in the CC editor and associated it with logical scripts and static resources, we directly transfer it from the editor’sLevel managerDrag toResource managerIt can be converted into prefabricated resources. However, since the association of resources within a CC is based on the resource path, it is necessary to put all the resources used by a CC component together before abstracting a CC component, so as to facilitate future reuse. Otherwise, it is likely to report the error of not finding resources when other projects reuse.

Create a new CC project and empty itassets/Directory, and then build in itComponents/Directory, as we store CC components directory. With the game results pageResultFor example, initialize according to the following directory structure and put in necessary resources:

.
 ν ─ ─ resources # component static resources
 │   ├──  score.png
 │   └──  star.png
 TS # Component Script

Then in CC editor, add pictures to child nodes by dragging and dropping, and finally tie up logical scriptsResult.ts

clipboard.png

When finished, drag it to the resource manager’sassets/Components/ResultDirectory to become a prefabricated resource.

In order to enable other users to use this component conveniently, a demo can be added to it, in which the scenes with this component only and the scripts required by the scenes are placed. When users need to know about this component, they only need to preview the Demo scene, and some methods of the component can also be seen in the Demo script. The final directory structure is as follows:

.
 The Demo # component uses DEMO
 │   ├── Result.fire
 │   └── ResultDemo.ts
 ν ─ ─ resources # component static resources
 │   ├──  score.png
 │   └──  star.png
 Prefab # component node
 TS # Component Script

clipboard.png

How to use

In short, as long as the component library engineeringComponents/The entire directory is copied to theassets/Directory, and then drag the prefabricated resource node to the hierarchy manager. Of course, such manual operation is not elegant enough, so we can use shell scripts to help us simplify this step.

Create a new one under the root directory of the target projectdownload.shScript, write the following:

#!  /bin/bash
 
 # Clean up first
 echo "Clearing workbench..."
 rm -rf ./cocos-components
 rm -rf ./assets/Components
 
 # clone the component library project directly, takes out the Components directory, and then deletes the component library project
 echo "Cloning project..."
 git clone  http://git.xxx.com/cocos-components.git
 cp -r ./cocos-components/assets/Components ./assets
 rm -rf ./cocos-components
 
 echo "Done!"

Only need to implement in the future./download.shYou can download to the latest component library, which is very convenient.

Component design specification

The design of components should follow the “black box” principle, which does not depend on other components or affect other components. The state of a component is saved by the component itself. If the state or behavior of the component needs to be changed, configurable items or interfaces should be exposed through it (the script instance of the component should be modified or introduced through the Cocos Creator’s property inspector).

In order toProgressTake the component as an example.

clipboard.png

It providesgameDurationConfiguration item that defines the countdown duration. In addition, it also provides asetTimeoutCallback()Is used to define the behavior when the countdown ends. The former can be modified directly in Cocos Creator’s property inspector, while the latter needs to be used in the game script through code:

import Progress from '../Components/Progress/Progress'
 
 @ccclass
 export default class Game extends cc.Component {
 start () {
 Progress.instance.setTimeoutCallback(() => {
 console.log('Test progress timeout callback!'  )
 })
 }
 }

When defining a script for a component, pay attention to adding a script namedinstanceFor calls between scripts:

export default class Progress extends cc.Component {
 static instance = null
 
 constructor () {
 super()
 Progress.instance = this
 }
 }

In addition, to build a component library, attention must be paid to naming specifications, so that both developers and callers can save a lot of trouble.

Subsequent optimization

CC Component Library Project is also a complete CC game. We can add a component menu to the game. Click on the menu to load the scene of the corresponding component and preview the effect of the component in real time. This idea will also be put into practice in the future and efforts will be made to open up new sources as soon as possible.