Vous êtes sur la page 1sur 296

Table

of Contents

Getting Started
Introduction 1.1
Install 1.2
Dashboard 1.3
Hello World 1.4
Quick Start 1.5
Cocos2d-x Guide 1.6
Unity Guide 1.7
Project Structure 1.8
Support 1.9

The Basics
Editor Overview 2.1
Assets 2.2
Scene 2.3
Hierarchy 2.4
Inspector 2.5
Console 2.6
Toolbar 2.7
Layout 2.8

Asset Workflow
Scene Managing 3.1
Sprite 3.2
Atlas 3.3
Font 3.4
Particle 3.5

1
Audio Asset 3.6
Prefab 3.7

Content Workflow
Node Component 4.1
Transform 4.2
Node Tree 4.3
Scene Editing 4.4

UI
Sliced Sprite 5.1
Multi-Resolution 5.2
Widget Align 5.3
Label Layout 5.4
UI Components 5.5
Auto Layout 5.6
List With Data 5.7

Animation
Animation 6.1
Animation Clip 6.2
Animation Curve 6.3
Sprite Animation 6.4
Time Curve 6.5
Animation Event 6.6
Scripting Animation 6.7

Components
Sprite 7.1
Label 7.2

2
Animation 7.3
Canvas 7.4
Widget 7.5
Progress 7.6
Button 7.7
Mask 7.8
Scrollview 7.9
Scrollbar 7.10
Layout 7.11

Scripting
Use Component 8.1
Properties 8.2
Access Node Component 8.3
Life Cycle Callbacks 8.4
Create Destroy 8.5
Events 8.6
Internal Events 8.7
Actions 8.8
Action List 8.9
Scheduler 8.10
Execution Order 8.11
Network 8.12
Pooling 8.13
Load Assets 8.14
Modular Script 8.15
Third Party Module 8.16
Web Debug Scripts 8.17
JavaScript Primer 8.18
Attributes 8.19

Publishing

3
Publish --> Web 9.1
Cocos Framework 9.2
Publish --> Native 9.3

4
Introduction

Cocos Creator

Cocos Creator, a free cross-platform game development editor supporting Cocos2d-js, helps
developers build 2D and 3D game scenes, edit game UI and other game resources quickly
and efficiency.

Q: Is Cocos Creator a game engine?


A: It's a complete game development solution, which includes the JavaScript realization
of Cocos2d-x(no need to learn a new engine), and various kinds of graph interface tools
that can help you develop games more quickly.

Q: What kind of editor does Cocos Creator have?


A: It's completely customized for the engine. It's an all-in-one editor that can serve the
whole workflow from design, development, preview, adjustment to release.

Q: Can I use Cocos Creator even if I don't know how to write a program?
A: Of course! Cocos Creator editor provides two kinds of workflows: one design-
oriented and one develop-oriented, and a simple and smooth cooperative method(with
an appropriate division of labor).

Q: Which platform can the games developed by Cocos Creator support?


A: Currently, Cocos Creator can release games on Web, Android, iOS, and the
click&play Cocos Play smartphone web-based game platform with original functions. It
can truly achieve the goal of one development for all platforms.

Product positioning
Cocos Creator is a game development tool focused on content creation, which has realized
features like thorough scriptability, componentization and data driven, etc. on the basis of
Cocos2d-x.

5
Introduction

Framework features
Cocos Creator contains a whole set of functions needed for game development like a game
engine, resource management, scene editing, game preview and release, etc. It has
assembled all the functions and tool in a unified application program.

It makes data driven and componentization the core game development methods, and
seamlessly integrates the mature JavaScript API system of the Cocos engine. It can adapt
to the user habits of the Cocos engine developer on one hand, and provide an
unprecedented level of content creation and realtime preview&test environment for
artworkers and directors on the other.

The editor provides not only strong and complete toolchains, but also an open plugin
framework. Developers can use generic front end technologies like Html + JavaScript, etc. to
conveniently extend functions of the editor and customize personalized workflows.

6
Introduction

What the combination of engine and editor brings is the functional development method of
data driven and componentization, and the perfect cooperation (with an appropriate division
of labor) of designers and programmers:

Designers build the image performance of scenes in scene editor


Programmers develop functional components that can be mounted to any object in the
scene
Designers are responsible for mounting components to objects that need to perform a
particular action and improving each parameter by adjustment
Programmers develop the data structure and resources needed for the game
Designers set up all the data and resources using the graphic interface
(In this way, from the simple to the complex, all the workflows that you can imagine can
be realized)

The development idea that focused on workflows can help developers of different duties
quickly find the breakthrough point to maximize their function at work and smoothly
cooperate with other group members.

Workflow introduction
In the development phase, Cocos Creator has already been able to greatly improve
efficiency and creativity for users. But the workflows we provided are not limited to a
development level. For a successful game, not only the whole set of workflows that form
development and adjustment, the assembly of commercialized SDK, multi-platform release,
test to going online can't lose a part, but also these workflows need iterations of lots of
times.

Cocos Creator integrates the whole set of smartphone web-based games of Cocos Play into
editor tools, so there is no need to switch between various softwares. Just open the Cocos
Creator editor, various one-click automatic flows can solve all the above problems with the

7
Introduction

least time and energy. Therefore developers can focus on the development phase, and
improve the competitiveness and creativity of products!

Functional features
The essential functional features of Cocos Creator include:

Data properties that can be adjusted in the editor at anytime can be easily declared in
the script. The adjustments to parameters can be independently finished by designers.
A UI system that supports smart canvas adaptation and spares the alignment of coding
elements can perfectly adapt to device screens of any resolution.
Animation system that is specially made for 2D games supports animation trajectory
preview and editing of complicated curves.
Scriptable development supported by a dynamic language makes dynamic adjustment
and the remote adjustment of mobile devices amazingly easy.
By using the Cocos2d-x engine, when enjoying the convenience of scriptable
development, you can also release games on various desktop platforms and mobile
terminal platforms with one-click, with their superb features on the original level
preserved.
Componentization of script and open plugin system provides developers with methods
of customizing workflows at different depths. The editor can be adjusted on a large
scale to adapt to the needs of different groups and projects.

Usage instructions
Cocos Creator is an applicable program that supports cross-platform operation between
Windows and Mac, which can be started with one double click. Comparing to traditional
Cocos2d-x workflows, it completely spares the requirements of setting up a development
environment. After running, developers can immediately start game content creation or
functional development.

On the basis of data driven workflows, the creation and editing of the scene has become the
core of game development. The design work and functional development can be done
synchronously and cooperated seamlessly. Regardless if your teammates are artworkers,
directors or programmers, they can all click the Preview button at anytime in the production
process to test the latest form of the game in browsers, mobile device simulators or mobile
devices.

8
Introduction

Programmers and designers now can realize various kinds of cooperative methods. No
matter building the scene before adding functions or creating functional modules to let
designers assemble and adjust them, Cocos Creator can always meet the needs of the
development group. Features defined in the script can present themselves in the editor with
the most suitable visual effects, which provides convenience for content creators.

Content resources outside the scene can be imported in, such as: photo, sound, altas,
skeleton animation, etc. Moreover, we are continuously improving the editor's ability of
creating resources, which include the currently finished animation editor. Designers can use
this tool to make very exquisite and vivid animation resources, and preview the animation in
the scene at anytime.

In the end, the finished game can be released on various platforms by using the on-click in
the graph tool. From design and development to test and release, Cocos Creator can handle
them all for you.

9
Install

Installation and Start


If you haven't downloaded and started Cocos Creator already, please start it according to the
following steps.

Download Cocos Creator


You can visit the download link on Cocos Creator products homepage to obtain the zip file of
Cocos Creator.

Directly decompress it to any location on the HDD after downloading.

Run Cocos Creator


On the Windows operating system, double click the CocosCreator.exe document in the
decompressed folder to start Cocos Creator.

On the Mac operating system, double click the decompressed CocosCreator.app icon to
start Cocos Creator.

You can set up quick start, Dock or a shortcut according to your preference for starting up
the program, allowing you to run it at any time.

Use Cocos developer account to login


If you don't need to release games on original platforms, the above two simple steps can
prepare for you a full developing environment for developing games using Cocos Creator.

After starting Cocos Creator, you will access the login interface for Cocos developer
accounts. After logging in, you can enjoy various kinds of online services, product upgrade
information and various developer benefits provided for developers.

If you don't have a Cocos developer account, you can use the sign up button in the login
interface to sign in to the Cocos developer center, or you can directly use the link below:

https://passport.cocos.com/auth/signup

10
Install

After signing up, you can go back to the login interface of Cocos Creator to complete the
login! After verifying your identity, you will be able to access the Dashboard interface. In
situations other than manual log out or the expiration of login information, the information
saved in the local session will be used for auto login.

11
Dashboard

Dashboard
After starting Cocos Creator and logging in with your Cocos developer account, the
Dashboard interface will open. You can create a new project, open an existing project or
obtain helpful information here.

Overview of the interface

What is listed above is the dashboard interface of Cocos Creator, which includes the
following types of tabs:

Recently Opened Projects: List projects that have been opened recently. When
running Cocos Creator for the first time, this list is blank and a 'Create a new project'
button will appear.
Create a New Project: By clicking this tab, you can access the guide interface for
creating a new project in Cocos Creator.
Open Other Projects: If your project is not in the list of recently opened projects, you
can click this button to browse and choose the project you want to open.
Help: Help information, which is a static page that includes various pieces of helpful
information and guides for beginners and documents.
Quick Start: Shows a video tutorial that can help you start using Cocos Creator to
develop games quickly.

Next, we will introduce these subpages one by one.

Recently Opened Projects


You can quickly access projects that have been opened recently by using Recently Opened
Projects. When running Cocos Creator for the first time, this list is blank and a 'Create a
new project' button will appear on the interface. You can come back here after having
created some projects. And you will see the newly created project appearing on this list.

12
Dashboard

When you hover your mouse over the article of a recently opened project, the available
operations on this article will appear:

Click Open and open this project in Cocos Creator editor


Click Close and remove this project from the list of recently opened projects. This
operation will not delete the actual project folder.

Also, when you click or hover over a project, you can see the path of this project in the
status bar underneath the Dashboard.

Create a New Project


You can create a new Cocos Creator project with the Create a New Project tab.

In the Create a New Project page, we first need to choose a project template. The project
template includes various kinds of basic game frameworks and sample resources and
scripts for learning, which can help you start creative work quicker.

13
Dashboard

Note: The early Cocos Creator edition doesn't include multiple optional project templates.
Along with the improvement of Cocos Creator's functions, we will gradually add more
templates to provide convenience for users.

Click a template, and you will see descriptions of this template at the bottom of the page.

At the bottom of the page, you will see the project name and the path that it's going to be
saved to. You can manually input the project path and project name in the input field of
project path. The last section of the path is project name.

You can also click the Browse button to open the input field of the browsing path. You can
choose a place in your local file system to store the new project.

After everything is set up, you can click the Create a New Project button to finish creating
the project. The Dashboard interface will be closed, and the newly created project will be
opened in the main window of Cocos Creator editor.

Open Other Projects


If you can't find your project on the Recently Opened Projects page, or if you just
downloaded a project that you have never opened before, you can browse and open the
project in the local file system by clicking the Open Other Projects button.

After clicking Open Other Projects, a selective input field of the local file system will pop up.
Choose your project folder in this input field and click "Open" and then you can open the
project.

14
Dashboard

Note: Cocos Creator uses a particularly structured folder as legitimate project marking, but
not it is not a construction document. You only need to click the project folder when choosing
the project.

Help
You can visit Cocos Creator User Manual and other helping documents by clicking the Help
page.

15
Hello World

Hello World
After understanding how to use the Dashboard, let's see how to create and open a Hello
World project now.

Create a New Project


In the Dashboard, open the Create a New Project tab and choose the Hello World project
template.

Then appoint the path of the new project in the project path bar below. The last section of
the path is the project folder.

After finishing inputting the path, click the Create a New Project button at the bottom right
corner, the project will be automatically created from the Hello World project template and
will be opened.

Open the scene and start working


The Workflow cores of Cocos Creator are data driven. When opening a project for the first
time, no scene will open by default. To view the content of the Hello World template, we
need to first open a scene resource document.

16
Hello World

Double click the Hello World scene document indicated by the arrow in the Resource
Manager. All the scene documents in Cocos Creator use ![../asset-
workflow/index/scene.png] as their icon.

Hello World project decomposition


After opening the Hello World scene, we can see all the contents of this template project.

17
Hello World

The content of the scene will respectively appear in four core panels resource manager,
arrangement manager, scene editor and property checker according to workflows.
Introductions to the editor interface and main panel will be shown in detail in the following
Editor Overview section.

Preview scene
To see a preview of the game scene, please click thepreview game button at the top of the
editor window.

Cocos Creator will use your default browser to run the current game scene. The effect is as
illustrated below:

18
Hello World

Click the drop down menu in the top left corner of the preview window and from here you
can choose the preview effects for different device screens.

Modifying the welcome message


The initial embodiment of Cocos Creator's focusing on data driven is that when we need to
change the welcome message of Hello Word, we don't need to edit the script code any
more, but can directly modify properties of the words that are saved in the scene.

Firstly click the Canvas node in the arrangement manager, to which our Hello World
component script is attached.

Next, find the Hello World component property at the bottom of the property checker, and
change the text in the Text property into Hello, world! :

19
Hello World

When running the preview again, we will see that the welcome message has been updated:

20
Hello World

Summary
The content of this section lets us know how to start the workflows of Cocos Creator from
the scene. And by modifying the welcome message, it gives a brief introduction to the
working methods of data driven. Next, we will lead you to finish a relatively complete leisure
game through a step by step process. We believe that you will have a more comprehensive
understanding Cocos Creator's workflows after this.

21
Quick Start

Quick Start:Creating your first game


The document you are reading now includes systematic introductions of the editor panel,
functions and workflows of Cocos Creator. However, if you want to quickly learn the general
flow and method of developing games by Cocos Creator, this chapter will meet your needs.
After finishing the tutorial in this chapter, you might obtain enough information for creating
games. But we still recommend you to continue reading this guide to understand the details
of each functional block and the complete workflows.

Now, let's begin! Following the tutorial, we will create a deceiving game that is named Pick
Up the Stars. Players of this game need to manipulate an obtuse monster that never stops
jumping to touch the continuously appearing stars. The dazzling acceleration will bring great
challenges to players. Play with your friends and see who can obtain the most stars!

The completed form of this game can be experienced here:

http://fbdemos.avosapps.com/star-catcher/

Prepare project and resources


We have prepared for you all the resources needed for creating this game. Download
Original Project and decompress it to the location you want. Then we can start:

Download the original project

You can also download the completed project. If there is any confusion when following the
tutorial to create the game, you can open the completed project for reference:

Download the completed project

Open the original project


If you still don't know how to obtain and start Cocos Creator, please read the Install section.

1. Firstly, start Cocos Creator, and choose Open other projects


2. In the pop up input field for selecting folder, choose start_project that has just been
downloaded and decompressed, and click the Open button
3. The main window of Cocos Creator editor will be opened, and you will see the project
status as follows

22
Quick Start

Check game resources


Our original project has included all the game resources needed; therefore, you don't need
to import any other resources. For details on importing resources, please read content
related to Asset Workflow.

Next, let's get to know the resources of the project. Please pay attention to a panel named
Resource manager, on which all the resource allocation graphs of the project are shown.

We can see that the root directory of the project resources is named as assets, which is in
accordance with the assets directory in the decompressed original project. Only resources
under this directory can be imported by Cocos Creator into the project and be managed.

Resource manager can display the directory structure of any hierarchy. An icon like
represents a folder. Clicking the triangle icon on the left side of the folder, you can unfold the
contents of the folder. After completely unfolding the folder, Resource manager will present
itself as illustrated below.

23
Quick Start

Every resource is a document, which, after being imported into the project, will be
recognized as different types of resources according to the differences in extension name.
Its icon will be differentiated too. Next, let's take a look at the respective types and usages of
the resources in the project.

audio document, which is an mp3 document generally. Audio documents named as


jump and score will be played respectively when the character jumps and scores.

bitmap font, which is jointly formed by a fnt document and png document. Bitmap font
is a commonly used font resource in game development. For detailed information,
please read Font
There are various kinds of abbreviated icons, all of which are image resources, normally
a png or jpg document. After being imported into the project, the image document will
be crudely processed into the resource of texture type. Then these resources can be
dragged into scenes or component properties for use.

Creating a game scene

24
Quick Start

In Cocos Creator, the game scene is the core of organizing the game contents when
developing games, which is also the carrier for all the game contents presented to players.
The game scene will normally include the following contents:

Scene images and words (Sprite, Label)


Characters
Game logic scripts attached to scene nodes in the form of components

When players run the game, the game scene will be loaded. After that, the game scripts of
included components will automatically run to realize various kinds of logic functions set up
by developers. Therefore, apart from resources, the game scene is the foundation of all
content creation. Now let's create a new scene.

1. Click the assets directory in the resource manager, making sure the scene will be
created under this directory
2. Click the plus sign on the top left corner of resource manager, and choose Scene in the

pop up menu
3. We created a scene document named as New Scene . Right click it and choose Rename
to rename it as game .
4. Double click game and the scene will be opened in the scene editor and arrangement
editor.

To understand Canvas

25
Quick Start

After opening the scene, all the nodes (and their hierarchical relations) of the current scene
will be shown in the arrangement manager. The newly created scene has only one node
called Canvas . Canvas can be called the canvas node or rendering root node. Click
Canvas, its properties will display in property checker.

The Design Resolution property here stipulates the design resolution of the game. Fit
Height and Fit Width stipulate how we should zoom Canvas to adjust to different

resolutions when running on screens of different sizes.

Being provided with the function of adjusting to different resolutions, we will normally put all
the nodes in charge of image display in the scene under Canvas. In this way, when the
scale property of Canvas changes, all the images, as its subnodes, will zoom together to

adjust to the sizes of different screens.

For more detailed information, please read Canvas. Currently, we only need to know that the
scene images added next will all be put under the Canvas node.

Setting up a scene image


Adding a background
First, find the background image resource according to the path of
assets/textures/background in resource manager. Click and drag this resource to the

Canvas node in Arrangement editor. Don't release the mouse until the Canvas node is
highlighted orange, which means a subnode using background as the image resource will
be added.

26
Quick Start

Now you can release the mouse button, and you will see a node named background has
been added under Canvas. When we use the way of dragging a resource to add a node, the
node will be automatically named as the name of the image resource.

When we edit and modify the scene, we can promptly save our modifications by main menu
document->save scene . Or we can save by shortcut keys: Ctrl+S(Windows)or Cmd +

S(Mac).

Modify background size

In scene editor, the newly added background images can be seen. Next we will modify the
size of the background image to make it cover the whole screen.

Firstly, click the background node, and click the fourth rectangle tool at the top left corner
of the main window:

By using this tool we can conveniently modify the size of the image node. Move the mouse
to rest on the left side of background in scene editor, click and drag it to the left until the left
side of background exceeds the blue frame that represents the design resolution. Then we
can drag the right side of background to the right using the same method.

27
Quick Start

Then we need to drag the upper and lower sides to make the size of the background image
fully cover the frame of the designing resolution.

When using rectangle tool to modify the size of the background image, we can see the
Size property of Node in property checker is changing accordingly. After completion, the

size of the background image is approximately (1360, 760) . You can also directly input a
numeric value into the input field of the Size property, which will achieve the same effect as
that of using rectangle tool. A background image of this size can cover the whole screen of
all the phones on the market, with no exceptions.

Add ground

28
Quick Start

Our main character needs a ground that it can jump on. We will add one instantly. By the
same method of adding a background image, drag the assets/textures/ground resource in
resource manager to Canvas in arrangement manager. When dragging, we can choose
the order relation of newly added nodes and background nodes. When in the state of
dragging the resource, move the mouse pointer to the bottom of the background node until
a highlighted orange frame appears on Canvas and a green line representing the insert
position appears below background , and then release the mouse. In this way, ground will
be put under the background in the scene hierarchy, which is also a subnode of Canvas .

In arrangement manager, the render order of nodes shown below will follow that of nodes
shown above. We can see the ground object at the bottom is the first to appear in scene
editor. Besides, the subnode will permanently display before the parent node. We can
adjust the hierarchical order and relation of nodes at anytime to control their show order.

According to the method of modifying the background, we can also use rectangle tool to set
a suitable size for the ground node. When activating rectangle tool, by dragging the
vertices and the parts other than the four sides of nodes, we can change the position of
nodes. The state of set ground nodes is as illustrated below:

Apart from rectangle tool, we can also use move tool

to change the positions of the nodes. Try to hold


down the arrow of move tool shown on the node and drag it, then we can change the
position of the node on a single coordinate axis at one time.

29
Quick Start

When setting up the position and size of the background and ground, we don't need precise
numeric values and can drag them by guessing. If you prefer whole numbers, you can
directly input numeric values of position and size according to the screenshot.

Adding a main character


Next our main character the little monster will make its debut. Drag
assets/texture/PurpleMonster from resource manager and put it under Canvas in

arrangement manager, and make sure its position is below ground , in this way our main
character will be shown at the very front.

To highlight the aura of the main character in the scene nodes, we right click the newly
added PurpleMonster node, choose rename and rename it as Player .

Next we will set up the properties of the main character. First, we change the position of
Anchor. The anchor point of any node will be at the center of itself by default, which means
the position of the center of the node is the position of the node. We hope to manipulate the
position of the base of the main character to simulate the effect of jumping on the ground;
therefore, we need to set up the anchor point of the main character under its foot now. Find
Anchor property in property checker and set up the value of y as 0 . We will see that in
scene editor, the arrow of the move tool that represents the position of the main character
appears under the foot of the main character.

Next, drag Player from scene editor and put it on the ground. The effect is as illustrated
below:

In this way our scene's basic artistic content is set up. In the next section we will write code
to vivify the contents of the game.

Writing the main character's script

30
Quick Start

One of the core ideas of developing games by Cocos Creator is to let the content creation
and function development undergo parallel cooperation smoothly. In the last section we
focused on artistic content. Next we will write script to develop the flow of functions, and we
will see that the finished program script can be used by content creators easily.

Even if you have never written a program before, there's no need to worry. We will provide
all the necessary codes in the tutorial. You only need to copy and paste them to the correct
position. Then in this part you can ask your programmer partners for help. Next let's start
creating script that drives the main character to act.

Create script
1. First, right click the assets folder in resource manager and choose Create->folder

2. Right click New Folder , choose Rename and rename it as scripts , under which all our
scripts will be saved.
3. Right click the scripts folder, choose Create->JavaScript and create a JavaScript
script
4. Rename the newly created script as Player . Double click this script and open the code
editor.

Writing component property


The opened script already has some preset code blocks. These codes are the structure
needed for writing a component script. Scripts of such a structure are the components in
Cocos creator, which can be mounted on the nodes in the scene and provide various
functions that manipulate nodes. First, we will set up some properties and see how to adjust
them in the scene.

31
Quick Start

Find the portion of properties in the Player script in code editor, change it to the
following content and press Ctrl + S(Windows)or Cmd + S(Mac)to save it:

// Player.js
//...
properties: {
// main character's jump height
jumpHeight: 0,
// main character's jump duration
jumpDuration: 0,
// maximal movement speed
maxMoveSpeed: 0,
// acceleration
accel: 0,
},
//...

These newly added properties will stipulate the movement of the main character. In code, we
don't have to care about how much these numeric values are, because we will directly set
up these numeric values in property checker later.

Now we can add the Player component to the node of the main character. Choose the
Player node in arrangement editor, click the add component button in property checker

and choose add user's script component->Player to add the Player component to the
node of the main character.

Now we can see the newly added Player component in property checker (need to choose
Player node). Set up properties related to the jumping and movement of the main

character according to the image below:

32
Quick Start

Only jumpDuration's unit is seconds. The unit of the other values is pixels. According to the
current setting of the Player component: Our main character will have a jump height of 200
pixels. The time needed for jumping to the highest point is 0.3 seconds. Its maximum
horizontal movement speed is 400 pixels per second. Its horizontal acceleration is 350 pixels
per second.

All these numeric values are suggestions. Later when the game is running, you can modify
these numeric values in property checker at anytime according to your preference, no need
to change any codes. How convenient it is, right!

Writing code for jumping and movement


Next we will add a method to make the main character jump. Add a method called
setJumpAction and put it under the properties: {...}, code block:

// Player.js
properties: {
//...
},

setJumpAction: function () {
// jump up
var jumpUp = cc.moveBy(this.jumpDuration, cc.p(0, this.jumpHeight)).easing(cc.
easeCubicActionOut());
// jump down
var jumpDown = cc.moveBy(this.jumpDuration, cc.p(0, -this.jumpHeight)).easing(
cc.easeCubicActionIn());
// repeat
return cc.repeatForever(cc.sequence(jumpUp, jumpDown));
},

Here some Action in the Cocos2d-js engine is used to realize the jumping animation of the
main character. For detailed information, please check Cocos2d-js API.

Next invoke the newly added setJumpAction method in the onLoad method and implement
runAction to start action:

33
Quick Start

// Player.js
onLoad: function () {
// initialize jump action
this.jumpAction = this.setJumpAction();
this.node.runAction(this.jumpAction);
},

The onLoad method will be immediately implemented after loading the scene. So we will put
operations and logic concerning initialization into it.

After the script is saved, we can start running the game for the first time!

Click the preview button at the top of Cocos Creator editor preview! Cocos Creator will
automatically open your default browser and run the game in it. Now we should see the main
character--a purple monster jumping lively and continuously in the scene.

Manipulation of movement
A main character that can only jump foolishly up and down on the same spot is not very
promising. Let us add keyboard input for the main character, using A and D to manipulate its
jump direction. Under the setJumpAction method, add the setInputControl method:

34
Quick Start

// Player.js
setJumpAction: function () {
//...
},

setInputControl: function () {
var self = this;
// add keyboard event listener
cc.eventManager.addListener({
event: cc.EventListener.KEYBOARD,
// When there is a key being pressed down, judge if it's the designated di
rectional button and set up acceleration in the corresponding direction
onKeyPressed: function(keyCode, event) {
switch(keyCode) {
case cc.KEY.a:
self.accLeft = true;
self.accRight = false;
break;
case cc.KEY.d:
self.accLeft = false;
self.accRight = true;
break;
}
},
// when releasing the button, stop acceleration in this direction
onKeyReleased: function(keyCode, event) {
switch(keyCode) {
case cc.KEY.a:
self.accLeft = false;
break;
case cc.KEY.d:
self.accRight = false;
break;
}
}
}, self.node);
},

Then modify the onLoad method, into which we add the switch of accelerating to the
left/right and the current horizontal speed of the main character. Then invoke the newly
added setInputControl method. Start monitoring keyboard input after loading the scene:

35
Quick Start

// Player.js
onLoad: function () {
// initialize jump action
this.jumpAction = this.setJumpAction();
this.node.runAction(this.jumpAction);

// switch of acceleration direction


this.accLeft = false;
this.accRight = false;
// current horizontal speed of main character
this.xSpeed = 0;

// initialize keyboard input listener


this.setInputControl();
},

In the end, modify the content of the update method by adding settings for the acceleration,
speed and the current position of the main character:

// Player.js
update: function (dt) {
// update speed of each frame according to the current acceleration direction
if (this.accLeft) {
this.xSpeed -= this.accel * dt;
} else if (this.accRight) {
this.xSpeed += this.accel * dt;
}
// restrict the movement speed of the main character to the maximum movement s
peed
if ( Math.abs(this.xSpeed) > this.maxMoveSpeed ) {
// if speed reaches its limit, use the max speed with current direction
this.xSpeed = this.maxMoveSpeed * this.xSpeed / Math.abs(this.xSpeed);
}

// update the position of the main character according to the current speed
this.node.x += this.xSpeed * dt;
},

update will be invoked once for each frame after loading the scene. We normally put the

logic contents that need to be frequently calculated or timely updated here. In our game,
after obtaining the acceleration direction by keyboard input, we need to calculate the speed
and position of the main character in update for each frame.

After saving the script, you can brew a cup of tea and click preview to check the latest
outcome. After opening the preview in your browser, click the game scene with the mouse
(due to the restrictions of browsers, keyboard input can only be accepted after clicking the

36
Quick Start

game scene) , then you can press the A and D buttons to manipulate the main character to
move to the left/right!

Is the movement a little bit too slow? Does the main character not jump high enough? Hope
to extend jump duration? No problem! All these can be adjusted at anytime. Just set up
different property values for the Player component, then you can adjust the game at your
will. Here is a set of settings for reference:

Jump Height: 150


Jump Duration: 0.3
Max Move Speed: 400
Accel: 1000

This set of property settings will make the main character as agile as possible. As for how to
choose the values, it all depends on what style of game you want.

Making stars
The main character can jump freely now so we need to set up a goal for players. The stars
will appear continuously in the scene and players need to manipulate the monster to touch
the stars for collecting points. The star touched by the main character will disappear and a
new one will be immediately re-created at a random position.

Create Prefab
As for the nodes that need to be created repeatedly, we can save it as a Prefab resource,
which can be a template for the dynamic generation of nodes. For more information about
Prefab, please read Prefab.

Firstly, drag the assets/textures/star resource from resource manager into the scene, the
position of which is not restricted. We only need the scene to be the operating platform for
creating Prefab. After creation we will delete this node from the scene.

We don't need to modify the position of the stars or render property. But to make the stars
disappear after being touched by the main character, we need to add a special component
to the star. By the same method of adding the Player script, add a JavaScript script named
Star to assets/scripts/ .

37
Quick Start

Next, double click this script to start editing. Only one property is needed for the star
component to stipulate the distance for collecting points by the main character. Modify
properties and add the following content:

// Star.js
properties: {
// When the distance between the star and main character is less than this val
ue, collection of the point will be completed
pickRadius: 0
},

After saving the script, add this script to the newly created star node. Then set up the
property value of Pick Radius in property checker as 60 :

38
Quick Start

The settings needed by Star Prefab are now finished. Now drag the star node from
arrangement manager and put it under the star folder in resource manager, then a
Prefab resource named star will be generated.

Now the star node can be deleted from the scene. We can dynamically use the Prefab
resource of stars in the script to generate stars.

39
Quick Start

Adding game control script


The generation of stars is a part of the game's main logic. Therefore we need to add a script
named Game and make it the script of the game's main logic. Logic concerning scoring,
failure and restarting will be added to this script later.

Add the Game script and put it under the assets/scripts folder. Double click to open the
script. First, add the properties needed for generating stars:

// Game.js
properties: {
// this property quotes the PreFab resource of stars
starPrefab: {
default: null,
type: cc.Prefab
},
// the random scale of disappearing time for stars
maxStarDuration: 0,
minStarDuration: 0,
// ground node for confirming the height of the generated star's position
ground: {
default: null,
type: cc.Node
},
// player node for obtaining the jump height of the main character and control
ling the movement switch of the main character
player: {
default: null,
type: cc.Node
}
},

After saving the script, add the Game component to the Canvas node in arrangement
editor (After choosing the Canvas node, drag the script to property checker or click the
Add component button in property checker and choose Game in User-defined script .
Next, drag the Prefab resource of star from resource manager to Star Prefab the
property of Game component. This is our first time to set up quotation for the property. Only
when setting type as quote type when declaring a property (such as the cc.Prefab type
written here) can a resource or a node be dragged to the property.)

Next, drag the ground and Player nodes from arrangement editor to properties of the
same name in the component to finish the node quotation.

Then set the values of the Min Star Duration and Max Star Duration properties as 3 and
5 . Later when generating stars, we will choose a random value between these two values,

which is the duration of the star.

40
Quick Start

Generate stars at a random position


Next, we will continue to modify the Game script by adding the logic of generating stars and
putting it behind the onLoad method:

// Game.js
onLoad: function () {
// obtain the anchor point of ground level on the y axis
this.groundY = this.ground.y + this.ground.height/2;
// generate a new star
this.spawnNewStar();
},

spawnNewStar: function() {
// generate a new node in the scene with a preset template
var newStar = cc.instantiate(this.starPrefab);
// put the newly added node under the Canvas node
this.node.addChild(newStar);
// set up a random position for the star
newStar.setPosition(this.getNewStarPosition());
},

getNewStarPosition: function () {
var randX = 0;
// According to the position of the ground level and the main character's jump
height, randomly obtain an anchor point of the star on the y axis
var randY = this.ground + cc.random0To1() * this.player.getComponent('Player')
.jumpHeight + 50;
// according to the width of the screen, randomly obtain an anchor point of st
ar on the x axis
var maxX = this.node.width/2;
randX = cc.randomMinus1To1() * maxX;
// return to the anchor point of the star
return cc.p(randX, randY);
}

After saving the script, click the preview button. Then in the browser you will see that a star
is dynamically generated after the game is started! By the same method, you can
dynamically generate any preset node with a Prefab template in the game.

41
Quick Start

Adding the action of the main character's touching and


collecting of stars
Now we will add the action logic of the main character's collecting of stars. The essential
point here lies in the fact that the star needs to obtain the position of the main character's
node at anytime to judge if the distance between them is shorter than the collectable
distance. How do we obtain the quotation of the main character's node? Don't forget that we
have done two things before:

1. There is a property named player in the Game component, which saved the quotation
of the main character's node.
2. Each star is dynamically generated in the Game script.

Therefore, we only need to deliver the concrete example in the Game component into a star
and save it after the concrete example of the Star node is generated in the Game script.
Then we can visit the main character's node by game.player at anytime. Let's open the
Game script, and add the following code to the end of the spawnNewStar method:

// Game.js
spawnNewStar: function() {
// ...
// deliver the concrete example of the Game component into the star component
newStar.getComponent('Star').game = this;
},

42
Quick Start

Open the Star script after saving, now we can use the player node quoted in the Game
component to judge the distance. Add the methods named getPlayerDistance and
onPicked and put them behind the onLoad method:

// Star.js
getPlayerDistance: function () {
// judge the distance according to the position of the player node
var playerPos = this.game.player.getPosition();
// calculate the distance between two nodes according to their positions
var dist = cc.pDistance(this.node.position, playerPos);
return dist;
},

onPicked: function() {
// When the stars are being collected, invoke the interface in the Game script
to generate a new star
this.game.spawnNewStar();
// then destroy the current star's node
this.node.destroy();
},

Then add the judging distance for each frame to the update method. If the distance is
shorter than the collectable distance set by the pickRadius property, implement collecting
behavior:

// Star.js
update: function (dt) {
// judge if the distance between the star and main character is shorter than t
he collecting distance for each frame
if (this.getPlayerDistance() < this.pickRadius) {
// invoke collecting behavior
this.onPicked();
return;
}
},

Save the script, then preview and test again. You will see that when the main character gets
close to the star, the star will disappear and a new one will be generated at a random
position!

Adding score
The little monster makes a great effort to collect the stars. But how come it receive no
reward? Now, let's add the logic and display of scoring when collecting stars.

43
Quick Start

Adding a score label(Label)


The score will start from 0 when the game is started. 1 point will be added for 1 star
collected. To display the score, we should first create a Label node. Choose the Canvas
node in arrangement manager, right click and choose create a new node->create a render
node->Label(word) . A new Label node will be created under Canvas , and it will be located

at the bottom. Next we will use the following steps to set up this Label node:

1. Change the node's name to score


2. Set the position of the score node( position property)as (0, 180) .
3. Set the size of the score node( size property)as (300, 80) .
4. Choose the node, edit string property of the Label component and input Score: 0 .
5. Set the Font Size property of the Label component as 50 .
6. Drag the assets/mikado_outline_shadow bitmap font resource from resource manager
(pay attention! the icon is )into the File property of the Label component, and
replace the font of the words with the bitmap font in the project resource.

The completed effect is as illustrated below:

Adding scoring logic to Game script

44
Quick Start

We will put the logic of scoring and updating the score display in the Game script. Open the
Game script to start editing. First, add a reference property of the score display Label to the

end of the properties block:

// Game.js
properties: {
// ...
// quotation of score label
scoreDisplay: {
default: null,
type: cc.Label
}
},

Next, add the initialization of variables for scoring in the onLoad method:

// Game.js
onLoad: function () {
// ...
// initialize scoring
this.score = 0;
},

Then add a new method named gainScore to the back of the update method:

// Game.js
gainScore: function () {
this.score += 1;
// update the words of the scoreDisplay Label
this.scoreDisplay.string = 'Score: ' + this.score.toString();
},

Invoke the scoring logic of the Game in Star script


Open the Star script after saving the Game script. Add the invoking of gainScore to the
onPicked method:

45
Quick Start

// Star.js
onPicked: function() {
// when the stars are being collected, invoke the interface in the Game script
to generate a new star
this.game.spawnNewStar();
// invoke the scoring method of the Game script
this.game.gainScore();
// then destroy the current star's node
this.node.destroy();
},

Preview after saving. You will see that when collecting stars, the scores displayed at the top
of screen will increase now!

Judgement of failure and restarting


Now our game has taken shape. But no matter how many scores one may get, a game
without the possibility of failure won't give players any fulfillment. Now let's add the action of
the stars' regular disappearance. And if all the stars disappear, the game will be viewed as
failed. In other words, players need to finish collecting the star before the star disappears
and repeat this procedure unceasingly to finish the loop of the play method.

Adding the logic of disappearing in a limited time to the star


Open the Game script, and add the variable declaration needed for counting time before
invoking spawnNewStar of the onLoad method:

46
Quick Start

// Game.js
onLoad: function () {
// ...
// initialize timer
this.timer = 0;
this.starDuration = 0;
// generate a new star
this.spawnNewStar();
// initialize scoring
this.score = 0;
},

Then add the logic of resetting the timer to the end of the spawnNewStar method, in which
this.minStarDuration and this.maxStarDuration are properties of the Game component

that was declared at the beginning. They are used to stipulate the random scale of star
duration:

// Game.js
spawnNewStar: function() {
// ...
// reset timer, randomly choose a value according the scale of star duration
this.starDuration = this.minStarDuration + cc.random0To1() * (this.maxStarDura
tion - this.minStarDuration);
this.timer = 0;
},

Add the logic of updating the timer and judgement of exceeding the duration to the update
method:

// Game.js
update: function (dt) {
// update timer for each frame, when a new star is not generated after exceedi
ng duration
// invoke the logic of game failure
if (this.timer > this.starDuration) {
this.gameOver();
return;
}
this.timer += dt;
},

In the end, add the gameOver method. Reload the scene when failure occurs.

47
Quick Start

// Game.js
gameOver: function () {
this.player.stopAllActions(); // stop the jumping action of the player node
cc.director.loadScene('game');
}

Modification of the Game script is now finished. Save the script and open the Star script,
because we need to add a simple visual prompt effect to the star that is about to disappear.
Add the following code to the end of the update method:

// Star.js
update: function() {
// ...
// update the transparency of the star according to the timer in the Game scri
pt
var opacityRatio = 1 - this.game.timer/this.game.starDuration;
var minOpacity = 50;
this.node.opacity = minOpacity + Math.floor(opacityRatio * (255 - minOpacity))
;
}

Save the Star script, and the logic of this game's play method will now be completely
finished. Now click the preview button, we will see a qualified game with a core play
method, incentive mechanism and failure mechanism in the browser.

Adding sound effects


Although lots of people will ignore sound when playing smartphone games, for the
completeness of the workflow presented in this tutorial, we still have to supplement the task
of adding sound effects.

Jumping sound effect


Firstly, add the jumping sound effect. Open the Player script and add the jumpAudio
property that quotes the sound document resource:

48
Quick Start

// Player.js
properties: {
// ...
// jumping sound effect resource
jumpAudio: {
default: null,
url: cc.AudioClip
},
},

Then rewrite the setJumpAction method, insert the callback of playing the sound effect and
play the sound by adding the playJumpSound method:

// Player.js
setJumpAction: function () {
// jump up
var jumpUp = cc.moveBy(this.jumpDuration, cc.p(0, this.jumpHeight)).easing(cc.
easeCubicActionOut());
// jump down
var jumpDown = cc.moveBy(this.jumpDuration, cc.p(0, -this.jumpHeight)).easing(
cc.easeCubicActionIn());
// add a callback function to invoke other defined methods after the action is
finished
var callback = cc.callFunc(this.playJumpSound, this);
// repeat unceasingly, and invoke callback to play sound after landing each ti
me
return cc.repeatForever(cc.sequence(jumpUp, jumpDown, callback));
},

playJumpSound: function () {
// invoke sound engine to play the sound
cc.audioEngine.playEffect(this.jumpAudio, false);
},

Scoring sound effect


After saving the Player script, open the Game script to add the scoring sound effect. Firstly,
we still add a property to properties to quote the sound document resource:

49
Quick Start

// Game.js
properties: {
// ...
// scoring sound effect resource
scoreAudio: {
default: null,
url: cc.AudioClip
}
},

Then insert the code of playing the sound into the gainScore method:

// Game.js
gainScore: function () {
this.score += 1;
// update the words of the scoreDisplay Label
this.scoreDisplay.string = 'Score: ' + this.score.toString();
// play the scoring sound effect
cc.audioEngine.playEffect(this.scoreAudio, false);
},

Save the script. Go back to arrangement editor, choose the Player node, and drag the
assets/audio/jump resource from resource manager to the Jump Audio property of the

Player component.

Then choose the Canvas node, drag the assets/audio/score resource to the Score Audio
property of the Game component.

Now it's done! The scene hierarchy of the completed form and properties of each key
component are as follows:

50
Quick Start

51
Quick Start

Now we can fully enjoy the newly created game. How many scores can you get? Don't
forget that you can modify game parameters like movement control and star duration, etc. in
the Player and Game components at anytime to quickly adjust the game's degree of
difficulty. The scene needs to be saved after modifications of component properties. Only the
saved values can be recorded.

Summary
Congratulations! You have finished the first game created by Cocos Creator. We hope this
quick start tutorial for beginners can help you understand the basic concepts and workflows
in the game development process of Cocos Creator. If you are not interested in writing and
learning script programming, you can directly copy and paste the completed script from the
completed project.

Next, you can continue to perfect this game. The following are some recommended
improving methods:

Add a simple start menu, display a start button when the game starts running. Only after
clicking the button will the game start
Add a simple menu interface for the failure of the game. Only after clicking the button
will the game restart after failure
Restrict the movement of the main character to the window's boundaries
Add more exquisite animation performance to the jumping action of the main character
Add a countdown progress bar to the state when a star disappears
Add more gorgeous effects when collecting stars
Add input controls for touch screen devices

For editions that have been improved in all the above aspects, you can download evolution
edition project for reference and learning, which will not be discussed in detail here.

Moreover, if you want to release the completed game on a server to share with your friends,
you can read the content of the Preview Build section.

Today's tutorial ends here. You can immediately start creating your second Cocos Creator
game or continue reading this guide. For any questions on this quick start tutorial, you can
send feedback on Warehouse of this tutorial on Github.

52
Quick Start

According to your experience of using the engine, you can continue to read:

Cocos2d-x User Guide


Unity User Guide

53
Cocos2d-x Guide

Cocos2d-x User Guide


Cocos Creator is a new type of game development tool oriented towards content creation
that has completely integrated the componentized edition Cocos2d-x WEB, by which you
can launch games on platforms like Web, iOS, Android, Mac, Windows, etc.. Moreover, you
can use it to directly launch games on Cocos Play platform, grasping the new opportunity
brought by the rapid development of the channel for mobile web games. For more
introductions to Cocos Creator, please refer to Introduction.

The aim of this document is to introduce the users of Cocos2d-x to Cocos Creator and help
them learn how to use the new editor as soon as possible. This document will discuss
possible problems that may occur in the transition from Cocos2d-x to Cocos Creator
development and offer relative solutions, which will not go deep into framework details but
provide links to detailed reference documents of different parts.

1. Typical Misconceptions
For new Cocos Creator users, some of the following typical misconceptions may occur:

1. Hoping to use Cocos Creator by coordinating it with Cocos2d-x:Cocos Creator,


having had a complete JavaScript WEB engine internally, can work without relying on
Cocos2d-x. However, if you want to launch the original edition, you still need to set up a
Cocos2d-x in your computer.
2. Building an entire code framework at first and then add in game contents:Cocos
Creator's workflows are content creation oriented, which is very convenient for
prototype creation. You can create scenes and write logic code directly into the editor,
then you can drive the game scene and run it. The following data driven chapters will
introduce changes of workflows in detail
3. Directly check the API of Cocos2d-JS when coding:Cocos Creator has said to be
originated from Cocos2d-JS. Their APIs have the same origin and have lots of identical
parts. But with entirely new componentized frameworks, their APIs are different and not
compatible with each other
4. Hoping to directly run the old Cocos2d-JS games on Cocos Creator:Their APIs
are not 100% compatible; therefore, such operation is unavailable.
5. Extend functions by way of inheritance:In Cocos2d-JS, inheritance is a basic
method for extending node functions. But in Cocos Creator, inheriting and extending
nodes is not recommended. The node is only an entity. The logic of the game should be
realized by different components and then be assembled in the node.

54
Cocos2d-x Guide

The reason for mentioning these misconceptions at the beginning of this document is that
we hope developers can realize that the workflows and development ideas provided by
Cocos Creator are tremendously different from those of Cocos2d-x. For a better
understanding of how to code correctly in Cocos Creator, the following two chapters will
introduce the changes in workflows and API level brought by data driven in more detail.

2. Data Driven
In Cocos2d-x, the development method is driven by code and most of the game's data is
stored in the code, unless the developer has built his/her own data driven framwork. In the
framework of Cocos Creator, all the scenes will be serialized as pure data. When running,
these pure data will be used to rebuild factors like scenes, interfaces, animations and even
components, etc..

What is code driven and what is data driven?


Why do we call Cocos2d-x a code driven development method? For instance, suppose that
there is a character in the scene, who will walk around continuously in one area, then we will
code as follows:

var role = new cc.Sprite('role.png');


scene.addChild(role);
role.setPosition(100, 100);
var walk = cc.sequence(cc.moveBy(5, 100, 0), cc.moveBy(5, -100, 0)).repeatForever();
role.runAction(walk);

In this code, scene relationship, position information, action section and animation
information of role are all realized by code; therefore it's called code driven. There also are
some developers who store data information in other documents, but they still have to
realize the parser of data themselves. Even when using some traditional editors, parsers are
also needed to parse the data exported from editors into scenes.

But what Cocos Creator provides is a more thorough data driven method. All the information
edited in the editor will be serialized into data documents. When running, the engine will
directly transform the data into object by deserialization. This procedure is fundamentally
different from the procedure described above: the category property in the engines can be
directly serialized or deserialized. You don't need to transform it by any mapping relation.
Scene graph, position property and animation, etc. in the above example can all be
serialized by the editor into data. When loading scenes, no data is needed, developers only
need to deserialize the whole scene from scene data:

55
Cocos2d-x Guide

cc.director.loadScene('SampleScene');

Serialization
Serialization and deserialization supports most public properties in Cocos Creator. These
properties are exposed to developers through the properties panel. Developers can
arbitrarily modify and save properties in editor. The procedure of saving is to serialize
resources and scene data into Asset Database. In contrast, in the procedure of loading
scenes, the deserialization mechanism can instantiate corresponding objects according to
scene data, and restore all properties set up in the editor.

What's more, the power of data driven lies in the fact that components edited by users
themselves can also make property declarations. These properties can be edited in editor,
saved in scene data, and finally deserialized into game scenes when running.

The source database is presented as Assets in the editor.

Understanding workflows of Cocos Creator from the angle


of data driven
Being different from Cocos2d-x, workflows of Cocos Creator are content creation oriented.
Developers might encounter various kinds of confusion in the process of transition. However,
when viewing from the angle of data driven, such changes of workflows will be a matter of
course. Data driven makes it possible to freely edit scenes. Developers can not only build
the whole scene visually, but also edit the logic of the game (edit properties exposed by
components), which makes the editor the access for all, but not code. Just like the example
before, in Cocos Creator, developers build a parent-child relationship, set position, and
design animation with editor at first, then design the logic of the nodes in the scene using the
component code; and assemble components into different nodes in the end.

56
Cocos2d-x Guide

3. Changes at Framework Level


As is mentioned at the beginning, Cocos Creator has been completely integrated with
componentized Cocos2d-JS. This is a highly customized edition. Due to componentization
and the needs of data driven, API sets and the standard edition of Cocos2d-JS have the
same origin, but the two of which are uncompatible with each other. The following are
detailed introductions of some important API differences:

Logic Tree and Render Tree


In Cocos2d-JS, the Render device will traverse the scene's node tree to generate a render
queue; therefore, the node tree built by developers is in fact a render tree. However, in
Cocos Creator, we introduce a new concept: logic tree. The node tree built by developers
and mounting components constitutes a logic tree, within which nodes constitute entity units
and components are in charge of logic.

The most essential difference is: What the logic tree concerns is game logic but not render
relation.

Th logic tree will generate the scene's render tree and decide rendering order. But
developers don't need to worry about these, they only need to make sure the correctness of
the displaying effect in editor. In Hierarchy of editor, developers can adjust the order and
parent-child relationship of the logic tree.

57
Cocos2d-x Guide

Scene Management
In Cocos2d-JS, after building scenes with code, developers can switch scenes by
'cc.director.runScene'. In Cocos Creator, when developers have finished building scenes in
editor, all the data will be saved as a 'scene-name.fire' document and then be stored in
Asset Database. Developers can load a scene resource by using cc.director.loadScene .
Please refer to the following concrete example:

var sceneName = 'scene-name';


var onLaunched = function () {
console.log('Scene ' + sceneName + ' launched');
};
// The first parameter is the name of the scene. The second optional parameter is the
callback function after the loading scene.
cc.director.loadScene(sceneName, onLaunched);

Besides, interface for visiting scene nodes is provided:

// To obtain scene nodes of logic tree


var logicScene = cc.director.getScene();

Node and Component


In Cocos Creator, 'cc.Node'is replaced by the logic node, and the old node is renamed as
_ccsg.Node and becomes a private category that is not recommended to be used anymore.

The reason for this is that developers only need to focus on logic nodes and they no longer
need to care about render nodes at the bottom. Of course, we have preserved its API sets
as much as possible. APIs like information concerning Transform, node tree, Action and
properties remain unchanged.

There used to be a crude mechanism of components. Developers could receive callbacks


like onEnter, onExit, update, etc. by adding components to Node. In Cocos Creator, the
same interface addComponent is used, but the component system becomes the core of the
whole engine. Components can extend the function of the logic node in various ways. It
could even be said that the logic node shouldn't include any actual game logic and it's logic
should be completely assembled by various kinds of logic components.

And this leads to the biggst difference between Cocos2d-JS and Cocos Creator: How to
extend node behavior?

In Cocos2d-JS, developers can extend Nodes. Cocos Creator does not allow this. All the
extensions should be done by adding components. In a componentized framework like
Cocos Creator, composition is the preferred extension method.

58
Cocos2d-x Guide

For more information on the component system, please refer to chapters like Node
Component and Components, etc..

Coordinate System and Anchor Point


The coordinate system of Cocos Creator is still a cartesian coordinate system, but there are
some changes in anchor points. Please look at the diagram before reading the explanations:

Supposing the anchor point of a context node is (0.5, 0.5). This node has a subnode, the
anchor point of which is (0, 0). In Cocos2d-JS, its illustration will be like that in the left
diagram. But in Cocos Creator, its illustration will be like that of the right diagram. The
reason is that the local coordinate systems of the subnodes are different. In Cocos2d-JS,
wherever the anchor point of the parent node is located, the origin of the subnode's
coordinate system is at the lower left corner of the parent node. But in Cocos Creator, the
origin of the subnode's coordinate system is in the position of the parent node's coordinate
position(i.e., its anchor point). Such modification is more compatiable with the editor, which
is, in general, very natural for scenes built by the editior. But when developers use code to
build nodes, they should pay special attention.

Categories and objects that remain unchanged


In Cocos Creator, we preserved the behaviors of lots of important categories and objects,
which include:

cc.game

cc.view

cc.director

59
Cocos2d-x Guide

cc.audioEngine

cc.eventManager

cc.scheduler

cc.textureCache

cc.sys

cc.visibleRect

scripting actions
Some types of render nodes: Menu and
MenuItem,ClippingNode,ProgressTimer,MotionStreak,ParallaxNode,RenderTexture,Dra
wNode,relative categories of Tile map, etc.
Chipmunk physics engine and PhysicsDebugNode
Types of basic data

Points to be noted:

1. Those types of preserved render nodes listed above can only interact with the render
tree and can't be used together with logic nodes and components.
2. Action system supports not just render nodes, but all the actions operated on Transform
support logic nodes too.
3. cc.scheduler supports components, which contain interfaces like

schedule , scheduleOnce , unschedule , unscheduleAllCallbacks

4. Though event manager is preserved, logic nodes have a set of new event API. Direct
use of event manager is not recommended. For detailed information, please refer to the
introduction of the event system that follows

Event System
In cc.Node , a series of wholly new event APIs are added. From logic nodes, various events
can be distributed. The monitor's register of some kind of event is also allowed. The monitor
could be a simple callback function, or an assembly of callback functions and its caller. List
of important APIs:

1. node.emit(type, detail) : Inform all the monitors to monitor type event. Capable of

sending an additional parameter.


2. node.dispatchEvent(event) : Send an event to its monitor. Support bubbling.

3. node.on(type, callback, target) : Continuously monitor type event of node .

4. node.once(type, callback, target) : Monitor type event of node once.

5. node.off(type, callback, target) : Cancel the monitoring of all type events or cancel

a certain monitor of type event (appointed by callback and target).

60
Cocos2d-x Guide

Such an event distribution method has changed from centralized distribution by


cc.eventManager to distribution by the node which has the event itself. It can be called a

transformation from a centralized event system to a discrete event system. In the meantime,
Cocos Creator has built in two kinds of system events(i.e., MOUSE and TOUCH ) in nodes:

Definition of enumeration object Corresponding event name


cc.Node.EventType.TOUCH_START 'touchstart'
cc.Node.EventType.TOUCH_MOVE 'touchmove'
cc.Node.EventType.TOUCH_END 'touchend'
cc.Node.EventType.TOUCH_CANCEL 'touchcancel'
cc.Node.EventType.MOUSE_DOWN 'mousedown'
cc.Node.EventType.MOUSE_ENTER 'mouseenter'
cc.Node.EventType.MOUSE_MOVE 'mousemove'
cc.Node.EventType.MOUSE_LEAVE 'mouseleave'
cc.Node.EventType.MOUSE_UP 'mouseup'
cc.Node.EventType.MOUSE_WHEEL 'mousewheel'

Henceforth, developers can directly respond to various MOUSE and TOUCH events of
nodes. They no longer need to judge whether contact points are included in nodes.
Moreover, the new event system supports event bubbling. Suppose the TOUCH event is
triggered on a node, if the event monitor didn't stop bubbling, its parent node would trigger
the same TOUCH event as well. For a concrete method of use for the event system, please
refer to Scripting Events

4. Next step
In a highly generalized way, the text above introduced some of the design ideas behind
Cocos Creator and obstructions that may occur when transitioning from Cocos2d-JS. Not all
the knowledge points are covered here. That's not the purpose of this document either. The
purpose of this document is to help Cocos2d-x users learn how to use Cocos Creator more
easily. Please continue reading the Cocos Creator User Guide, getting to learn all of the
workflows and coding techniques.

61
Unity Guide

Unity User Guide


For users who have used Unity3D before, they will find it extremely easy when starting to
use Cocos Creator because many concepts are interlinked between the two. However, there
still are some differences between Cocos Creator and Unity3D on some detailed concepts.
This document will enumerate the differences between Cocos Creator and Unity3D to help
Unity3D users learn to use Cocos Creator more quickly.

Abstract
Cocos Creator Unity3D Instruction
Object in
the scene.
Each object
cc.Node GameObject
can contain
many
components
Set up the
activated
node.active gameObject.activeSelf
state of the
node itself
Check the
activated
node.activeInHierarchy gameObject.activeInHierarchy state of the
node in
hierarchy

node.parent transform.parent
Position in
Cocos
Creator is in
the local
coordinate
node.position transform.position system, but
in Unity3D
it's in the
world
coordinate
system

Rotation in
Cocos
Creator is in
the local

62
Unity Guide

coordinate
node.rotation transform.rotation system, but
in Unity3D
it's in the
world
coordinate
system
node.scale transform.localScale
If refNode is
blank, find it
from the
scene root
transform.Find(path),
cc.find(path, refNode) node,
GameObject.Find(path)
otherwise,
find it from
the refNode
node.

cc.game.addPersistRootNode(node) Object.DontDestroyOnLoad(gameObject)
cc.Component Component Component
comp.node comp.gameObject
comp.onLoad() comp.Awake()
comp.start() comp.Start()
comp.update(dt) comp.Update()
comp.lateUpdate(dt) comp.LateUpdate()
obj is the
concrete
example of
cc.Object
obj.destroy() Object.Destroy(obj)
(normally it
is: node,
component
or asset)

Judge if
cc.Object is
effective
cc.isValid(obj) obj != null (normally it
is: node,
component
or asset)

The API of Firball use camelCase. The first letter of the method and variable is in
lowercase. The first letter of the category definition is in uppercase.
The callback of Firball follows the style of Node.js, which means the first parameter of
the callback is wrong information.

63
Unity Guide

cc.Node vs GameObject
Node in Cocos Creator equals to GameObject + Transform in Unity3D. In Cocos Creator, the
hierarchical relation of the parent and child nodes is maintained by Node. But in Unity3D, it's
in the charge of Transform.

// change the parent-child relation


this.node.parent = anotherNode;

// rotate by 20 degrees
this.node.rotation += 20;

// shift by pixcels of (10,10)


this.node.position.x += 10;
this.node.position.y += 10;

// zoom in/out for 1.5 times


this.node.scale.x *= 1.5;
this.node.scale.y *= 1.5;

Coordinate system
position , rotation and scale in cc.Node are both in the local coordinate system. As for

Unity3D, its Postion , Rotation is in the world coordinate system.

In Cocos Creator, if you want to calculate the world coordinate of cc.Node, you can use the
following method:

// set up the node to the position of (100,100) in world coordinate system


this.node.position = this.node.convertToNodeSpaceAR(cc.v2(100,100));
// this.node.rotation = TODO

cc.Component vs MonoBehaviour
In Cocos Creator, the user defined script is written by extending the cc.Component category.
But in Unity3D, it's written by extending MonoBehaviour. Let's compare a Cocos Creator
script with a Unity3D script that has the same functions:

Unity3D:

64
Unity Guide

public class Foobar : MonoBehaviour {


public string text = 'Foobar';
void Start () {
Debug.Log('Hello ' + text );
}
void Update () {}
}

Cocos Creator:

// Foobar.js
cc.Class({
extends: cc.Component,
properties: {
text: 'Foobar',
},
onLoad: function () {
console.log('Hello ' + this.text);
},
update: function (dt) {},
});

Property definition
In Cocos Creator, properties are defined in the properties field. But in Unity3D, properties
are defined as member variables of MonoBehaviour. Apart from differences in the defining
positions, Cocos Creator also imports the concept of the property parameter into the
property. These parameters can be used to control the display method of properties in
Inspector, serialization, etc. For detailed parameters, please refer to:
[/manual/scripting/attributes]

The following are defining methods of some commonly used properties in Cocos Creator:

65
Unity Guide

var MyEnum = cc.Enum({


Foo: 1,
Bar: 2,
});

// MyScript.js
var Foobar = require('Foobar');
cc.Class({
extends: cc.Component,
properties: {
// quote other cc.Node
// in Unity3D, it is defined as: public GameObject otherGameObject;
otherNode: { default: null, type: cc.Node },

// quote a concrete example of Foobar Component


// in Unity3D, it is defined as: public Foobar foobar;
foobar: { default: null, type: Foobar },

// do not serialize this property


// in Unity3D, it is defined as: [System.NonSerialized] public int index = 0;
index: { default: 0, type: cc.Integer, serializable: false },

// define an array
// in Unity3D, it is defined as: public float[] idList;
idList: { default: [], type: cc.Float },

// define an enumerated category


// in Unity3D, it is defined as: public MyEnum myEnum = MyEnum.Foo;
myEnum: { default: MyEnum.Foo, type: MyEnum },
}
})

Life cycle
The life cycle of Cocos Creator is basically the same as Unity3D, having only slight
differences in the naming:

66
Unity Guide

Cocos Creator Unity3D

onLoad Awake
start Start
update Update

lateUpdate LateUpdate
onEnable OnEnable
onDisable OnDisable
onDestroy OnDestroy

When you want to destroy a cc.Object concrete example (such as: node, component or
asset), you can use obj.destroy() function.
When you want to determine whether a cc.Object concrete example(such as: node,
component or asset) is destroyed or not, you can use cc.isValid(node).

Message
The message system of Cocos Creator uses the transmit&receive mode of dom, which can
send a message upward, but you need to sign up for message in Node. But in Unity3D,
messages are realized by going through SendMessage and directly responding to the
member function defined in the script.

The following is the transmit&receive mode of message in Cocos Creator:

cc.Class({
extends: cc.Component,

onLoad: function () {
this.node.on('hello-foobar', function ( event ) {
event.stopPropagation();
console.log('Hello Foobar');
});
},

start: function () {
this.node.emit('hello-foobar');
},
})

67
Project Structure

Project structure
Using the Dashboard, we can begin by creating a Hello World project. The created project
has a specific folder structure. We will learn about the Cocos Creator project in this section.

Project folder structure


After creating and opening a Cocos Creator project for the first time, you will see the
following structure is included in the project folder:

ProjectName(project folder)
├──assets
├──library
├──local
├──settings
├──temp
└──project.json

Next we will introduce the function of each folder.

Resource folder(assets)
‘assets’

Public folders for project collaborators


assets Project resource files, including all actual elements used to form a project.
Such as:
Scenes
Scripts
Sprites
Textures
Audio files
... Just think of all of them as loaded resources in the Assets Panel of the
[Editor](/start/editor-overview)
settings These are global project settings, which are of a project-level and are
shared by all project collaborators, such as:
Plug-in settings
Button settings
Physics settings

68
Project Structure

...
Private folders used by the current client (and you should ignore them in version control)
library Files in this folder are for resource library management, and will be used by
the Editor for library data persistence and resource display.
local Local project settings, which store the user's customized settings, such as the
Editor layout.
temp Temporary files created by the Cocos Creator Engine.

69
Support

Obtain help and support

Send problems and feedback


Apart from the information provided in this guide, you can also obtain information from or
send feedback to the Cocos Creator development group through the following channels at
any time:

QQ group:246239860
Cocos2d-JS API document
Q&A community

Presentation and example projects


Example collection: from basic components to interactive input, this project includes
usage case by case introductions to the functional points.
Your first Cocos Creator game: Star Catcher
21 points card game co-developed with Tencent

Original release code library


Cocos code libraries that are needed for zipping and sending to native platforms (Windows,
Mac, Android, iOS):

Cocos Framework v3.9 Windows Edition


Cocos Framework v3.9 Mac Edition

Code libraries needed for zipping and sending to the Android platform:

Android SDK Windows


Android SDK Mac
Android NDK Windows 32bit
Android NDK Windows 64bit
Android NDK Mac

Other third-party tools and resources

70
Support

Tools for generating texture packer


TexturePacker
Zwoptex

Tools for generating Bitmap font


Glyph Designer
Hiero
BMFont (Windows)

2D skeleton animation tools


Spine
Spriter
DragonBones

Tools for making special effect particles


Particle Designer
Particle2dx: free online tool

Other game development resources


Cocos Store: various game art assets, extension tools

71
Editor Overview

Editor interface overview


This chapter will introduce the editor interface and get familiar with each of the panels,
menus and functional buttons that make up the editor. The Cocos Creator editor is
composed of multiple panels which can be moved and combined freely to meet the needs of
different projects and developers. Here we will take the default editor layout as an example
to quickly browse the name and function of each panel:

Asset manager

72
Editor Overview

Asset manager shows all the assets in the project asset file (‘assets’). It will show the folder
in a dendritic structure and auto-sync the content changes in the project resource folder from
the operating system. You can drag files in or use the menu to import resources.

For further information please read the asset manager section.

Scene editor

73
Editor Overview

Scene editor is used to show and edit the visible working area in the scene. WYSIWYG
scene building work is all done depending on the display in the scene editor.

For further information please read the scene editor section.

Hierarchy

74
Editor Overview

Hierarchy displays all the nodes and their hierarchy in the form of a list tree. For all the
content you can see in the scene editor, the corresponding node entry can be found in the
Hierarchy. The content in these two panels when editing the scene will synchronize the
display and we normally use these two panels at the same time to build the scene.

For further information please read the Hierarchy section.

Attribute inspector

75
Editor Overview

Attribute inspector is the working area where we view and edit the currently selected node
and component attribute. This panel will display and edit the attribute data defined by the
script in the most suitable way.

76
Editor Overview

For further information please read the Inspector section.

Toolbar

Toolbar includes the scene editing tool and operating button for game preview. The far right
side shows the access address for remote testing and debugging and the device number of
the connected device.

Continue on to read about Toolbar.

77
Assets

Assets
Assets is used for us to access and manage the working area of project assets. Adding
assets in here is normally a necessary step when starting to make game. You can use
HelloWorld template to create a new project and then you can see there are many basic
asset types in assets.

Introduction for the interface


assets shows the contents in project assets folders in tree view, but be noticed that only the
assets put under assets catalog in the project folder will be showed in here. Please read
Project structure for project folder structure. Now let me introduce the elements in each
interface:

78
Assets

Create button on the top left corner is used to create new asset
The input box on the top right can be used to search and filter the asset filenames that
contain specific text.
The main part of the panel is the asset list for the asset folder where you can add,
delete or alter assets using context menu or dragging operation.

Asset list
Asset list can include any folder structure. Folders in assets will show as icon. Click the
arrow on the left to the icon, the contents in this folder will be unfold/fold.

The rest showed in the list other than folders are all asset files. Files in the asset list will not
show their expanded-names, instead, they will use icons to indicate the type of file or asset,
for example, the project created by HelloWorld template includes three core assets:

79
Assets

image assets:currently includes image files like jpg and png , icon will show as
thumbnail of the image.
script assets: the JavaScript file programmer writes and uses js as the filename
extension. We add function and game logic to the component by editing these scripts.
scene assets: scene file opened by double click. Only the scene file is opened can
we keep creating and making the contents.

More common asset types and asset workflow, please read Asset workflow.

Create assets
Currently, the assets can be created in assets are as follows:

Folder
Script file
Scene
Movie clips

Click create button on the top left corner, the create assets menu including the above asset
list will be popped out. Click any item in it will create new corresponding assets at the current
selected position.

Select asset
You can use the following asset selection in asset list:

Click to select a single asset


Press Ctrl or Cmd on the keyboard and click the mouse to join more assets into the
selection

80
Assets

Press Shift on the keyboard and click the mouse to select continuous assets

You can execute move, delete and other operations to those selected assets.

Move asset
After selecting the asset(can select many for once), hold down the mouse and drag to move
the asset(s) to other position. Drag the assets into the folder, you will see the folder with the

mouse hovering over is highlighted by orange.


Release the mouse at this time so that the asset(s) is moved into the highlighted folder.

Delete asset
For those chosen assets, you can execute the following operation to delete:

Right click and choose delete from the popped out menu
Press Delete(Windows)or Cmd + Backspace(Mac) after choosing the asset

Since deleting assets is an irreversible operation, there will be a dialog box popped out
demanding user to confirm. Once click yes, the assets will be deleted permanently and
cannot be found in recycling station (Windows) or trash bin (Mac)! Please use it with caution
and do version management or manual backup.

Other operations
The right click menu of assets also includes the following operation:

rename : rename the asset

create : same function with create button, it will add asset to the current selected

folder. If the current selected one is asset file, it will add new asset to the same folder
with current selected asset.
show in explorer(Windows)or Finder (Mac) : open the asset folder in the file manager

window of operating system.


Go to the asset location in Library : open the imported asset location in Library of

81
Assets

project folder. Please read project structure for detailed information.


Show UUID : show the current selected asset's UUID inconsole window.

Refresh : rerun the import operation of this asset.

Besides, for specific asset type, you can enter the editing status like scene asset and script
asset by double clicking asset.

Filter asset
Enter text in the search box at the top right of assets to filter filenames with all the assets
including the input text. You can also input filename extensions like *.png so it will list all
the assets with this specific extension.

82
Scene

Scene editor

Scene editor is the core working area of content creation. You will use it to choose and
place the scene image, character, special effet, UI and other game elements. In this working
area, you can select and use transform tool to change the node's attributes like position,
rotation, scale and size. Here you can also preview WYSIWYG scene effect.

View Introduction
Navigation
You can move and locate the view in scene editor by the following operations:

right click to drag:horizontally remove the view.


mouse wheel:zoom in/out the view by taking the current mouse hovering position as
the center.

Coordinate system and grid


There will be a set of scaleplate and grids on the background of the scene view, which
indicate the position information of each point in world coordinate system. Point reads
(0,0) is the origin of the world coordinate system in the scene. When using the mouse

wheel to zoom out the view display, each scale represents a distance of 100 pixel. Due to
the differences in the zooming in/out scale of current view, the number representing the
distance from this point to origin will display on different scales, the unit of which is pixel.

83
Scene

Scale and grid in the scene are important reference information for us to place the scene
elements. For informations on the relationship between coordinate system and node
attributes like position, please read Transform section.

Indicator Frame of Design resolution


The purple frame in the view represents the content area that displays in the scene by
default. The size of this area is determined by design resolution. For settings and effects of
deign resolution, please read Canvas section.

Select a node
When the mouse is hovering on the node in the scene, the constraint frame of the node will
display a grey singlet line. The node will be selected if you left click the mouse. You can only
use transform tools (like position, rotation) to set node operations after selecting it.

There will be wireframe in blue around the selected node to prompt the constraint frame for
node.

Node name prompt


When the mouse is hovering on the node, the node name will be displayed together with the
node constraint frame. You can decide your target before clicking to confirm your selection
according to the suspend prompt at places where nodes are gathering.

About the naming of nodes, please read the introduction in Hierarchy.

The node constraint box


You can see the constraint box(in grey or blue) when hovering on or selecting the node, and
the rectangular region of the constraint box indicates the size attribute size of the node.
Even though the node doesn't contain image rendering component(such as Sprite), you can
set size attribute for the node and the tranparent region within the constraint box of node
can be selected by clicking the mouse or hovered.

84
Scene

Node's size attribute plays an important role in multiresolution adapt and layout strategy.
For more information about usage of node size, please read multiresolution adapt and
elements aligning.

Multiselect nodes
Press the left mouse button and drag in scene editor and you can draw a blue marquee.
Nodes overlap with the marquee will be selected all together when releasing the mouse. You
can slide the mouse at your will to change the marquee area before releasing the mouse.

After selecting multiple nodes, any transform operation will make effects on all the selected
nodes.

Use transform tool to arrange node

85
Scene

The core function of scene editor is to edit and arrange the visible elements in the scene in
the way of WYSIWYG. We mainly arrage the nodes in the way we hope them to be by series
transform tool on the top left corner of the main window's tool bar.

Move transform tool


Move transform tool is the tranform tool default in activated state when opening the editor.
This tool can be activated by clicking the first button on top left corner of main window's tool
bar.

Select any node so you can see the node center(or anchor's position) appears a gizmo
composed of red and green arrows and blue cube.

Gizmo refers to a controller that can interactive with mouse and appears in certain editing
states in the scene editor. These controllers are only to assist editing without being shown in
the game while it is running.

When the move transform tool is activated:

Press red arrow and drag mouse, then the node will be moved on the x axis;
Press green arrow and drag mouse, then the node will be moved on the y axis;
Press blue cube and drag mouse, then the node will be moved freely on both the
axises.

When the scene editor is activated, press keyboard shortcut W and you can switch to move
tranform tool at any time.

86
Scene

Rotate transform tool


Click the second button on the tool bar located at the main window's top left corner or press
the keyboard shortcut E in scene editor and you can activate rotate transform tool.

The gizmo of rotate transform tool is mainly made up of an arrow and a circle. The direction
of arrowhead indicates the angle of current node rotation . By dragging arrow or any point
in the circle, you can rotate the node and you can get the angle value of current rotation on
gizmo before you release the mouse.

Scale transform tool


Click the third button on the tool bar located at main window's top left corner or press the
keyboard shortcut R in the scene editor and you can activate scale transform tool.

Press red arrow and drag mouse, then the node will be zoomed on the direction of x
axis;
Press green arrow and drag mouse, then the node will be zoomed on the direction of y
axis;
Press the yellow square in the middle, then the whole node image will be zoomed

87
Scene

keeping the aspect ratio.

All the child nodes will be zoomed in the same ratio with the node.

Rectangle tranform tool


Click the fourth button on the tool bar located at the main window's top left corner or press
the keyboard shortcut T in scene editor and you can activate rectangle tranform tool.

Drag any end-points of the gizmo so you can change the attributes of width and height in
node size while the opposite angles end points position keep the same.

Drag any side on the gizmo so you can change the attributes of width and height in node
size while the opposite sides position keep the same.

88
Scene

In UI elements layout, rectangle transform tool is always used to precisely control the
position and length of the node's dimensions. As to the image elements that must keep
original image aspect ratio, the rectangle transform tool is normally not the best choice for
size adjustment.

89
Hierarchy

Hierarchy

Hierarchy includes all nodes in current opened scene, no matter the node includes the
visible image or not. You can choose, create and delete nodes in here and create set
membership of node by dragging one node to another.

Click to choose node, and the selected node will be highlighted in blue. Current selected
node will show with blue frame in scene editor and update contents in Inspector.

Create node
There are two ways to create node in Hierarchy:

90
Hierarchy

Click + button on the top left corner or right click the mouse to enter the create node
submenu in right click menu. In this submenu, you can select different node types
including Sprite, Label, Button and other nodes with different functions and expressions.
Drag assets like image, font or particle from explorer to Hierarchy. Then you can create
corresponding image rendering node with the selected assets.

Delete node
After select node, you can delete the selected node by the delete option in the right click
menu or press the hot key Delete(Windows)or Cmd + Backspace. If the selected node
contains child node, then the child node will be deleted along with it.

Establish and edit node hierarchy relationship


Dragging node A to node B makes node A the child node of node B. Similar with explorer,
Hierarchy also show nodes' hierarchical relationship in tree view. Click the triangle icon on
the left of node and you can unfold or fold the child node list.

Change node's showing order


Other than dragging one node to another, you can also keeps dragging node up and down to
change the order of node in the list. The orange square indicates the range of parent node
which the node belongs to and the green line represents the position the node will be
inserted.

91
Hierarchy

The ranking of node in the list determines the showing order of node in the scene. The lower
the node is in the Hierarchy, the later will its rendering happen in the scene and will cover
the nodes rank higher in the list.

Other operations
Right click the node, the popup menu also includes the following operation:

Copy/paste:copy the node to the clipboard and then paste it to other places or open
another scene to paste the node just copied.
Copy node:generate node replication exactly the same with the selected node and
they are at the same level.
Rename:rename the node
Show route in console:In complicated scenes, we sometimes need to get the
complete hierarchy route of the node to access it when running the script. Click this
option so you can see the node's route in console.

92
Inspector

Inspector

93
Inspector

Attribute inspector is the working area where we check and edit the current selected nodes
and component attributes. Select the node in Scene editor or Hierarchy, attributes of this
node and attributes of all the components of this node will display in Inspector for your

94
Inspector

inquiry and editing.

From top to bottom, the Inspector panel displays:

node activating switch and node name


node attribute
component attribute

node name and activating switch


The check box on the top left corner indicates the activating state of node. When the used
node is not activated, all the components related to image rendering on the node will be shut
down. The whole node including child nodes will be hidden efficiently.

What displays at the right side of the node activating switch is node name, which is in
accordance with the node name showed in Hierarchy.

Node attribute
Next, Attribute inspector will show the attributes of node, which are listed under the
headline Node . By clicking Node , one can fold or unfold the attributes of node.

Other than the transforming attributes like Position, Rotation, Scale and Size, node attributes
also include Anchor, Color, Opacity. Generally, modifications of node attributes will
immediately reflect in the changes in the appearance or position of node in scene editor.

For more details on node attribute, please read Transform section.

Component attribute
All the components mounted to a node and their attributes will be listed under node attribute.
Just like node attribute, you can switch the fold/unfold status of a component attribute by
clicking its name. When there are many components mounted to a node, you can get larger
working area by folding the component attributes that are not frequently modified.

Users create a component by script, the attribute of which is declared by the script. Different
types of attributes have different widget appearances and editing methods in Inspector. The
defining method of attribute will be introduced in detail in Scripting Properties.

Edit an attribute

95
Inspector

Attribute is a public variable that declared in the component script and can be serialized
and stored in the scene and animation data. We can quickly modify the attribute settings by
Inspector to realize the goal of adjusting game data and playing method with out
programming.

Normally we can divide attributes into value type and reference type according to the
different memory location used by variables.

Value type attribute


value type includes numbers, strings, enumerations and other simple variable types that
occupy small RAM space:

Number: can be input directly by keyboard. Users can also press the upward/downward
arrows near the input field to gradually increase/decrease attribut value.
Vec2: the widget of Vec2 is the combination of two input values. And the input field will
mark the corresponding child attribute name of each value with x and y .
String: directly use keyboard to input string into textbox. The input widget of string can
be divided into two types: single line and multiple lines. Users can press Enter button to
wrap in Multiple lines textbox.
Boolean: It can be edited in the form of check box. The selected state indicates the
attribute value is true ; and the non-selected state indicates the attribute value is
false .

Enum: It can be edited in the form of drop-down menu. Click enum menu and choose
one option from the popp up menu list, then the modification of enum can be finished.
Color: click color attribute preview box and color picker window will popped out. You
can click to choose the color you need in this window, or directly enter specified color in
the RGBA color input box below. Click any position outside the color picker window will
close the window and the color selected in the end will be took as the attribute color.

96
Inspector

Reference type attribute


Reference type includes much more complicated objects, such as node, component or
asset. Different from the various editing methods of value type, reference type normally has
only one editing method--drag the node or the asset into the attribute column.

The attribute of reference type will show None after the initialization. Because users can't
use script to set up initialized value for attribute of reference type, they can drag
corresponding nodes or assets according to the type of attribute to finish the assignment for
reference type.

The attribute column that needs to be assigned value by dragging nodes will show green
label. There might display Node on the label, which means any node can be dragged into it.
Also, the label may display component names like Sprite , Animation , etc., then users
need to drag the nodes to which corresponding components are mounted.

The attribute column that needs to be assigned value by dragging assets will show yellow
labels. There might display the asset type on the label, such as sprite-frame , prefab ,
font , etc.. The assignment can be finished as long as you drag the assets of

corresponding type from resource manager.

97
Inspector

Note: that script file is also a type of asset. Therefore the script asset reference attribute
used by components shown on the top of the above picture is also represented by a yellow
label.

98
Console

Console

console will report errors, warnings or other log informations generated by Cocos Creator
editor and engine. Information with different priority will show in different color:

Log:gray text, is normally used to indicate operation on-going.


Info:blue text, is used to indicate important prompt information.
Success:green text, is used to indicate that current operation has successfully done.
Warn:yellow text, is used to warn user to deal with the abnormal situation which won't
influence operations if not being dealt with.
Error:red text, indicates gross error and measures must be took before going on to
the next operation or running the game.

When there are too much information in console, you can filter these information effective by
widgets in console. The operations include:

Clear Clear all the current information in console panel.


Filter input Filter the information in console according to the input
text. If the Regex next to it is checked, then the input text will be took as a regular
expression to match the text.
Information levels You can choose one information level from this drop-
down menu. From log level to error level, console will only show information in specific
level. The default option All represents information in all levels will be showed.
Merge same type information When this selection is being activated,
the same and repeat information will be merged into one, but there will be yellow
numbers next to the information to prompt how many information of the same type have
been merged.

99
Console

100
Toolbar

Tool bar

Tool bar is right above the main editor window including five sets of control buttons or
pieces of information that provide editing functions for specific panels and allow the user to
conveniently implement workflows.

Choose transform tool

This provides the editing node transform attribute (position, rotation, scale, size) function for
the scene editor. Please refer to use transform tool to place node for detailed information.

Transform tool display mode


Control the display mode of the transform tool in scene editor with the two sets of buttons
below.

Position mode:

Anchor: transform tool will be displayed at the position where the node Anchor is.
Central point: transform tool will be displayed at the position where the central point of
the node is (influenced by the constraint box size).

101
Toolbar

Rotation mode:

Local transform tool's rotation (handle direction) will stay the same as the Rotation
attribute of the node.
World: transform tool's rotation stays the same and the handles of the x and y axes stay
the same as the direction of the world coordinate.

Run game preview

This includes two buttons:

Run preview: run the scene being currently edited in the browser.
Refresh device: reload the current scene on all the devices that are connected to this
machine to preview the game (including local browser and other mobile devices
connected to the native machine).

Preview address

Here is shown the LAN address of the desktop computer running Cocos Creator. The mobile
devices connected to the same local area network can access this address to preview and
debug the game.

Open project folder

Open the project folder in the operating system explorer or finder.

102
Toolbar

Continue on to read about the Editor Layout.

103
Layout

Editor layout
Editor layout refers to the position, size and stack of panels in Cocos Creator.

Select the Layout menu from the main menu and you can choose the most suitable editor
panel layout from the pre-set ones for your current project. You can adjust the position and
size of each panel on the basis of the pre-set layout. Alterations to the layout will be auto-
saved to the local/layout.windows.json file in the project folder.

Adjusting panel size


Position the mouse on the border line of two panels and drag when the cursor changes
shape to change the size of the two adjacent panels.

104
Layout

Some panels have a minimum size setting, so the panel size can't be reduced if it reaches
its size limitation.

Moving panels
Click the tab bar on the panel and drag to move the whole panel to any position in the editor
window. The red box in the picture below shows the tab bar area that can be dragged and
the arrow shows the drag direction:

105
Layout

The blue translucent box shows the position where the panel will be placed once the mouse
is released when moving the panel.

Stacking panels
Besides moving the panels, you can also move the mouse to the tab bar area of another
panel when dragging the tab bar:

106
Layout

Release the mouse when the tab bar appears orange, so that the two panels can be stacked
together. Only one panel can be displayed at a time:

Panels in a stack can be very practical when the desktop resolution is not enough or the
panel layout usage rate is low. Panels in a stack can be dragged out at any time to recover
the display of the panel that is placed at the top.

107
Scene Managing

Creating and managing scenes

Creating a scene
Method one: on the main menu select File-->New scene

Method two: click the create menu in assets to create a new scene.

108
Scene Managing

Saving a scene
Method one: use keyboard shortcut Ctrl + S (Windows) or Command + S (Mac)

Method two: on the main menu select File-->Save scene

Switching scenes
Double click the scene that you want to open in assets.

109
Sprite

Texture
Coming soon...

110
Atlas

Atlas
Coming soon...

111
Font

Font
Coming soon...

112
Particle

Particle System

Importing a particle asset


Put the Cocos2d-s supported particle .plist directly under the project catalogue.

Adding a particle system to the scene


Method one: drag particle assets directly from assets to Hierarchy:

113
Particle

Method two: drag particle assets directly from assets to scene editor:

114
Particle

Method three: add a ParticleSystem component to the existing node and give particle
assets to the component File attribute in assets:

115
Particle

116
Audio Asset

Audio asset
Coming soon...

117
Prefab

Prefab

Creating a prefab
After editing the Node in the scene, drag it directly from Hierarchy to asset:

And thus you create a prefab:

Saving prefab
After changing the prefab object in the scene, click apply in the Inspector and you can save
the corresponding prefab:

118
Prefab

Reverting prefab
After changing the prefab object in the scene, click revert in the Inspector and you can
restore the corresponding prefab to the status in asset:

119
Node Component

Node and component


The core of Cocos Creator's workflow is component-based development. The component-
based framework is also known as the component-entity system (or Entity-Component
System). Simply put, we construct the entity in combination mode instead of inheriting mode.

In Cocos Creator, a Node is an entity carrying component. We will make nodes that have
many kinds of expressions and functions by mounting a Component that has many kinds of
functions itself on the node. Let’s see how to create a node and add a component to the
scene.

Create Node
To get a node having a specific function fastest, you can use the create node button on the
left corner of the Hierarchy. We can make a very simple Sprite node as an example. Click
the create node button and then choose ’create rendering node/Sprite’:

Then we can see the new Sprite node in the scene editor and Hierarchy. The new node is
named ‘New Sprite’, meaning this is a node whose function is mainly provided by the Sprite
component. You can also try clicking the create node button again to choose other node
types so that you can find their different names and expressions.

Component
Sprite component

120
Node Component

Now since we have some nodes, let's see what a component is and the connections
between the components and nodes. Select the ‘New Sprite’ that we just created and you
can see what the Inspector says:

121
Node Component

The part starting with ‘Node’ in the Inspector is the property of the node. The property of the
node includes changeable information about the node like position, rotation, scale and size
as well other information such as anchor, color and opacity. We will introduce each in detail
in the node properties section.

In the following picture, the part starting with ‘Sprite’ is the property of the Sprite component.
In 2D games, the Sprite component is responsible for most of the image rendering. The
most important property of the Sprite component is ‘Sprite Frame’ where we can designate
the image files that Sprite is going to render in the game. Let's try to drag a picture resource
from the resource manager to the ‘Sprite Frame’ property in the Inspector:

We see that the previous Sprite default image turns into the image we assigned. This is what
the Sprite component does: rendering images.

The influence of the node attribute on the Sprite component


When a node combines with the Sprite component, the rendering method of an image can
be controlled by modifying the node attribute. You can adjust your node according to the
settings marked by red lines in the following picture. You can see that the image rotation,
scale, color and opacity changes:

122
Node Component

We mentioned earlier that the component based structure achieves function extensions by
combining. The following picture shows how the node and the Sprite component combine.

Node Color and Opacity property

123
Node Component

The property of Color and Opacity in the above picture have direct influence on the Sprite
component rendering image. Color and opacity can also influence the display of the
rendering component Label.

These two properties will multiply the content of the rendering component itself to determine
each pixel's color and opacity during rendering. In addition, the Opacity property will act on a
child node and easily achieve the fade in and fade out effect of a set of node contents by
altering the ‘Opacity’ of the parent node.

Add other components


We can add multiple components on one node to add more functions to the node. In the
example above, we can continue to select the ‘New Sprite’ node, click the add component
button at the bottom of the Inspector panel and select ‘add UI component/Button’ to add a
Button component.

Then set the Button component according to the following picture (the actual color attribute
can be set freely according to your own taste):

124
Node Component

Next, click the operation preview button on the toolbar and


hover the mouse over the image in the browser operation window. You can then see the
color of the image changes which means the adding of the Button component to the node

125
Node Component

has taken effect!

Brief Summary
In the above example, we first combined the Sprite component with the node which led us to
the scene image that could designate the resource for the rendering image. Then we could
display this image in different ways by altering the node attributes like scale and color. Next
we could even add a Button component to the node so that it could react according to the
different statuses of the button (normal, hover, down, etc.). This is the component based
development workflow in Cocos Creator. We can use this method to combine different
functions within a node to achieve a series of complicated targets, such as a character's
mobile attack controls, auto scrolling of background images, layouts of UI elements,
interaction functions and so on.

It's worth mentioning that a single node can only add one rendering component including
Sprite, Label, Particle and so on.

Reference reading
Understand component-entity system - i_dovelemon's blog

126
Transform

Coordinate system and node


transformation attribute
In the Scene editor and Node and component files, we introduced that we can change a
node's display behaviour by using change tools and editing the node's attributes in the
Inspector . We will learn more about the coordinate system of where the node is and the
operating principles of the node's four transformation attributes of Position, Rotation, Scale
and Size in this section.

Cocos Creator coordinates system


We have learnt that we can set the position attribute for a node, so where will a node with a
specific position attribute be displayed on the screen when the game is operating? Like a
map in real life, we can run satellite positioning using both longitude and latitude. We also
need to learn about the coordinate system of Cocos Creator to understand the meaning of
node positioning.

Cartesian coordinate system


The Cocos Creator coordinate system is exactly the same as the cocos2d-x engine
coordinate system. The cocos2d-x and OpenGL coordinate systems both originated from the
Cartesian coordinate system. In the Cartesian coordinate system, the origin of the right-
handed system is in the lower left corner with the direction of x going towards the right, y
going upwards and z going outwards. This coordinate system we use is called the Cartesian
right-handed coordinate system.

127
Transform

Screen coordinate system and cocos2d-x coordinate


system
The standard screen coordinate system uses a different coordinate system from OpenGL. It
is very different from the cocos2d-x coordinate system.

The coordinate system used in developing applications with native SDK in iOS, Android,
Windows Phone and other platforms is the standard screen coordinate system. The origin is
located at the screen upper left corner with x going towards the right and y going
downwards.

The cocos2d-x coordinate system is the same with the OpenGL coordinate system, the
origin is in the lower left corner while x goes towards the right and y upwards.

World Coordinates and Local Coordinates

128
Transform

The world coordinate system is also called the absolute coordinate system. It is a united
coordinate system for displaying the scene space during Cocos Creator game development.
「World」is used to indicate the scene in our game.

The local coordinate system is also called the relative coordinate system and it is related to
the node. Each node has its own unique coordinates, so when the node is moving or
changing directions, the coordinates related to this node will also move or change directions.

Nodes in Cocos Creator can have a hierarchical structure of set membership. The node
position we altered in the node's Position attribute setting are the local coordinates
relative to the parent node not the world coordinates. Finally, when drawing the entire scene
Cocos Creator will map these nodes' local coordinates to the world coordinates.

To determine the function mode of the coordinate system for each node, we also need to
understand the concept of anchor.

Anchor
Anchor is another important property of nodes. It determines which point in the constraint
frame of the node itself should be taken as the position of the whole node. The position we
see the transformation tool show after we choose the node is the anchor position of the
node.

Anchor is expressed by anchorX and anchorY which are multiplication factors in the range
of 0 ~ 1 . They calculate the anchor position by using the node size. (0.5, 0.5) indicates
the anchor is located in the position where the node length and width are both multiplied by
0.5, i.e. the center of the node.

129
Transform

When the anchor attribute is set as (0, 0) , the anchor is located at the origin of the node's
local coordinates, i.e. the left bottom corner of the node constraint frame.

130
Transform

The local coordinates of the child node


Once the anchor position is decided, all the child nodes will take the anchor position as the
coordinate origin. One thing we need to note is this action is not the same as the default
action in the cocos2d-x engine; it is a feature of the Cocos Creator coordinate system!

Hypothetically, the node structure in the scene is as follows:

When our scene contains nodes from a different hierarchy, we should take the following
steps when we determine the position of each node in the world coordinate system:

1. Process each node from the root level of the scene. ‘NodeA’ in the above image is a
root level node. First, determine the display position and coordinate origin position
(same as the anchor position) according to the Position and Anchor attributes of
NodeA.
2. Then process all of the direct child nodes of NodeA, i.e. ‘NodeB’ and its sibling nodes.
In NodeA's local coordinate system determine the position of NodeB in the scene space
and the position of the origin of the coordinate system.
3. No matter how many levels that the nodes have, we process them all in order from
highest level to the lowest. Each node should use the coordinates of the parent node
and its own position anchor attribute to determine position within the scene space.

Transform property
Besides the Anchor we introduced above, the node also includes four other main
transformation properties which we will introduce next.

131
Transform

Position
Position is composed of ‘x’ and ‘y’ properties which set the node coordinates on the x and y
axes of the current coordinates.

‘NodeA’ in the above image is at the root level of the scene. Its position is ‘(507, 354)’ (refer
to the scale on the background of thescene editor), the position of its child node ‘NodeC’ is
‘(345, 0)’. You can see that the position of the child node migrated based on the parent
node's anchor.

The default value of the position property is ‘(0, 0)’ which means that the newly added node
will always show up at the parent node's coordinate origin position. The default position of
nodes in Cocos Creator is ‘(0, 0)’ and the default anchor is set as ‘(0.5, 0.5)’. Nodes under
this setting will be located at the center position of the parent node by default so that all the
contents can be taken in when making UI or combining a player's character.

132
Transform

In the scene editor, you can always use move transform tools to change a node’s position.

Rotation
Rotation is another important property that will have an effect on a node’s local coordinates.
The rotate property only has one value to indicate the current rotation angle of the node.
When the angle value is positive, the node rotates clockwise; when the angle value is
negative, the node rotates counter clockwise.

The node hierarchical relationship in the image above is the same as in the previous image
only with the Rotation attribute of ‘Node’ set as ‘30’ degrees. As well as ‘NodeA’ itself
rotating 30 degrees clockwise, its child node ‘NodeC’ also rotates 30 degrees clockwise
taking the anchor of ‘NodeA’ as the center.

In the scene editor, you can always use rotate transform tools to change the rotation of a
node.

Scale
The Scale property is a set of multiplication factors which are composed of scaleX and
scaleY to represent the scale percentage of a node on the x and y axes.

133
Transform

The scale property of ‘NodeA’ in the above image is set as ‘(0.5, 1.0)’. This means the node
is reduced by factor of 0.5 on the x axis and remains the same on the y axis. You can see
the image of its child node NodeC is also reduced on the x axis, so the scale property will
influence all the child nodes.

The scale property set on the child node will have additive effects on the parent node. The
child node of a child node will multiply all the scale properties on each hierarchy to get the
scale percentage used in the world coordinate system. This is the same case with the
position and rotation properties, it’s just that that position and rotation properties have
additive effects, while the scale property makes the effects more obvious by multiplication.

The scale property acts on the effects of the properties of position and size among others.
When you change the scale property, the node's position and size won't change, but it will
multiply the position, size and other properties by a scale before showing the node image;
the values from the multiplication are the actual position and size of the node that will
appear.

In the scene editor, you can always use scale transform tools to change the scale of the
node.

Size
The Size property is composed of ‘Width’ and ‘Height’ to stipulate the constraint frame's size.
For the Sprite node, the size of the constraint frame is the size of the image that will appear.

134
Transform

Therefore, the size property can easily be confused with the scale property. They both can
influence the size of the Sprite image, but they influence it in different ways. The size
property, along with position and anchor, regulates the four endpoint positions of the node
and determines the image display range of the constraints of these four points according to
its result. The size property plays a vital role in rendering the Sliced Sprite.

Meanwhile, the scale property gets the node's width and height after scaling based on the
multiplication of the size value. When determining the size of the image, size is the basis
while scale is the variable so to speak. Besides, the size property will not influence the size
of the child node (but can make an indirect influence through Widget), which is very different
from the scale property.

In the scene editor, you can always use rectangle transform tools to change the node size.

135
Node Tree

Manage node hierarchy and display order

136
Scene Editing

Build scene graph with scene editor


Coming soon...

137
Sliced Sprite

Use a Sliced Sprite to make a UI image


When developing UI, we usually use an image in a nine rectangle grid format to display US
element, the size of which might be dynamically modified according to the requirements of
fitting screen resolution. In this way, even a very small original picture can be used to
generate a background image that can cover the whole screen. It will save the inclusive
space of the game, on the other hand, it can flexibly fit different layout requirements.

The right side of the picture above displays the texture of original size. The left side displays
the effect of choosing Sliced mode and enlarging the size property.

The nine rectangle grid cutting of the image


resource
To use a nine rectangle grid image effect that can be infinitely enlarged, we need to cut the
image resource into a nine rectangle grid at first. There are two methods to open Sprite
editor to edit the image resource:

Choose image resource in resource manager, then click the edit button on the bottom
of property checker. If the height of your window is not large enough, you might need
to scroll property checker downward to see the button at the bottom.
Choose the image node that you want to cut into a nine rectangle grid in scene editor.
Then find and click the Edit button on the right side of the Sprite Frame property in the
Sprite component of property checker.

138
Sliced Sprite

After opening Sprite editor, you will see there is a green line around the image, which
indicates the position of the current split line of the nine rectangle grid. Drag the mouse to
the split line, you will see the shape of the cursor change, then you can press down and drag
the mouse to modify the position of the split line.

We drag the four split lines on the left/right/upper/lower side respectively and cut the image
into a nine rectangle grid. The nine areas will apply different zooming in/out strategies when
the Sprite size changes, which is as illustrated below:

And the following picture illustrates the state of zooming in/out in different areas (the picture
comes fromYannick Loriot's Blog):

139
Sliced Sprite

After cutting, don't forget to click the green check mark on the upper right corner of Sprite
editor to save modifications to the resource.

Set Sprite component to use Sliced mode


After preparing the resource that has been cut into a nine rectangle grid, you can modify the
display mode of the Sprite. And by modifying size , you can create a UI element whose
size can be arbitrarily designated.

1. First, choose the Sprite node in the scene, set Type property of the Sprite as Sliced .
2. Then drag the controlling point by rectangle tool to enlarge the size property of the
node. You can also modify the size property by directly inputting a numeric value into
property checker. If the image resource is produced in a nine rectangle grid format,
then no matter how much the Sprite zooms in, no vagueness or distortion will appear.

Notice
When using rectangle tool or directly modifying the size property of a Sliced Sprite, don't
set the value of size as a negative number, otherwise it can't be displayed correctly in
Sliced mode.

Continue on to read about Multi-resolution

140
Multi-Resolution

Fit scheme for multi-resolution


Cocos Creator is devoted to solving the problem of adapting to screens with various
resolutions with one set of resources from the beginning. Generally speaking, we realize the
adaptation scheme for multi-resolution through the following technology:

Canvas component immediately obtains the actual resolution of the device screen and
appropriately adjusts the size of all the render elements in the scene.
Widget is put on rendering elements, which can align the element with different
referential positions of the parent node according to different needs.
Label component has a built-in function that provides various dynamic layout modes.
When the bounding box of labels change because of the alignment requirement of the
Widget, labels will present the perfect layout effect according to your needs.
Sliced Sprite provides images whose size can be arbitrarily designated.
Simultaneously, it can meet various alignment requirements and display images with
high definition on screens of any resolution.

Next, we start off by getting to know the concepts of design resolution and screen resolution,
then we will go on to make understanding of the zooming in/out function of the Canvas
component.

Design resolution and screen resolution


design resolution is the resolution sample used by content creators when creating the
scene. But screen resolution is the actual resolution of the device that the game is running
on.

Normally, design resolution will use the screen resolution of the device that is being used the
most by the targeted group on the market, such as: screen resolutions of 800x480 and
1280x720 that are being used by Android devices currently, or screen resolutions of

1136x640 and 960x640 that are being used by iOS devices. Therefore, after designers or

directors set up the scene by using design resolution, the game will automatically adapt to
the device used by the major targeted group.

Then when the design resolution is different from the screen resolution, how could Cocos
Creator adapt to the device?

Supposing the design resolution is 800x480 , designers will create a background image of
the same resolution.

141
Multi-Resolution

When design resolution and screen resolution have the


same ratio of width to height
When design resolution and screen resolution have the same ratio of width to height,
supposing the screen resolution is 1600x960 , enlarging the background image to 1600/800
= 2 times will perfectly fit the screen. This is the simplest situation, which will not be
discussed in detail here.

When the ratio of width to height of design resolution is


larger than that of screen resolution, the height should be
adjusted to avoid black borders
Supposing the screen resolution is 1024x768 , a red frame is used in the following picture to
indicate the visible area of the device screen. We use Fit Height mode provided by the
Canvas component to make the height of the design resolution automatically cover the
height of the screen, i.e., enlarging the scene image to 768/480 = 1.6 times.

142
Multi-Resolution

This is a fairly good adaptation mode when the ratio of width to height of the design
resolution is larger than that of the screen resolution. As illustrated above, although some
parts of the background image will be cut down on the two sides of the screen, it can be
ensured that no goof or black borders will appear in the visible area of the screen. Then the
position of UI elements can be adjusted by the Widget, which makes sure that the UI
elements will appear in the visible area of the screen. We will introduce this in detail in the
next section Widget Align.

When the ratio of width to height of the design resolution is


larger than that of the screen resolution, the width should
be adjusted to avoid black borders
Supposing the screen resolution is 1920x960 , a red frame is also used in the following
picture to indicate the visible area of the device screen. We use Fit Width mode provided
by the Canvas component to make the width of the design resolution automatically cover the
width of the screen, i.e., enlarging the scene to 1920/800 = 2.4 times

143
Multi-Resolution

When the ratio of width to height of the design resolution is relatively small, the use of this
mode will cut down some parts of the background image on the upper/lower sides of the
screen.

No matter how much the ratio of width to height of the


screen is, all the contents of design resolution will be
completely displayed, and black borders are permitted.
In the last example, supposing the screen has a resolution of 640 x 960 . If you want to
make sure the background image is completely displayed on the screen, you need to
simultaneously open Fit Height and Fit Width in the Canvas component. The zooming
in/out proportion of the scene image is calculated according to the smaller dimension in the
screen resolution. In the example in the following picture, because the ratio of width to height
of the screen is less than 1, the calculation of the zooming in/out proportion will be based on
width, i.e., 640/800 = 0.8 times.

144
Multi-Resolution

Under such a displaying mode, there might be black borders on the screen or scene image
that exceed the design resolution (goof). Although developers try their best to avoid black
borders in general, if you want to make sure all the contents within the scale of design
resolution are displayed on the screen, you can use this mode too.

According to the ratio of width to height, 'Fit Width' or 'Fit


Height' will be automatically chosen.
If there are no strict requirements for the content that might be cut down on the four sides of
the screen, you don't need to open any fit mode in the Canvas component. Then Fit Height
or Fit Width will be automatically chosen according to the ratio of width to height to avoid
black borders. In other words, when the ratio of width to height of the design resolution is
larger than that of the screen resolution, 'Fit Height' will be automatically opened (as in the
first picture above); when the ratio of width to height of the design resolution is smaller than
that of the screen resolution, 'Fit Width' will be automatically opened(as in the second picture
above).

Canvas component doesn't provide a fit mode that can


respectively zoom in/out of the x axis and the y axis, which
will distort the image.

145
Multi-Resolution

In the Cocos engine, there is a fit mode called ExactFit , which doesn't have black borders,
or cut down the image within the scale of design resolution. But the price is the zooming
in/out ratio of the scene image to the direction of the x/y axis is different, which will distort the
image.

If you don't mind distortions of the image, you can use the engine API to realize fit effect
without using the Canvas component. For detailed information, you can refer to Cocos2d-
JS's screen adaptation scheme.

Use Canvas component in the scene


When creating a new scene, a node including the Canvas component will automatically be
added to the root node of the scene. On the Canvas component, the options mentioned
above can be set:

Design Resolution
Fit Height
Fit Width

Set the Canvas node as the root node of all the render nodes of the image, then these
nodes can automatically use the zooming in/out effect of Canvas's intelligent adaptations to
multi-resolution.

146
Multi-Resolution

The features of Canvas when editing the scene


When editing the scene, the Size property of the Canvas node will be the same with
design resolution, which can't be modified manually.

The Position property will remain at (width/2, height/2) , which is the center of the
screen whose resolution is the same with the design resolution.

Because the default value of the Anchor property will be set as (0.5, 0.5) , the Canvas
will remain at the position of the screen center. The subnode of Canvas will make the screen
center the origin of its coordinate system, which is different from that in the Cocos engine.
Please pay attention to that.

The features of Canvas when running


Apart from the above features, the Canvas component will have the following changes in
features:

Scale: According to the calculating principle of the zooming in/out ratio described
above, assign the calculated zooming in/out ratio to the Scale property.
Size: In the mode without black borders, the Size property of Canvas will remain the
same as the screen resolution. In the mode with black borders, the Size property of
Canvas will remain the same as the design resolution.

Because Canvas can precisely obtain the size of the visible area of the screen when
running, we can set up the alignment strategy of UI elements according to this size, making
sure that all the UI elements can be correctly displayed in the visible area of the screen.

147
Widget Align

Alignment strategy
To realize a perfect multi-resolution fit effect, presenting UI elements according to the
positions stipulated in the design resolution is not enough. When the width and height of the
screen change, UI elements must be able to intelligently sense the positions of the borders
of the screen to make sure that they are presenting themselves in the visible area of the
screen and being distributed in suitable positions. Such an effect can be realized by Widget.

Next, we categorize different alignment workflows according to the categories of elements


that need to be aligned:

Buttons and small elements that need to be


aligned by borders
For elements with relatively small areas like a pause menu, in-game gold coins, etc.,
normally, aligning them by the borders of the screen would be enough. Then only a few
simple steps are needed:

1. Set these elements as subnodes of the Canvas node in arrangement manager


2. Add the Widget component to element nodes
3. Taking alignment with the bottom left corner as an example, open the alignment of
Left and Bottom .

4. Then set up the distance between the node and the borders of the screen. In the picture
below, the left margin is set as 50px, right margin is set as 30px.

148
Widget Align

After setting up the Widget component like this, no matter what the actual screen resolution
is , this node element will remain on the bottom left corner of the screen. The distance
between the left side of the node's bounding box and left border of the screen remains at
50px. The distance between the bottom of the node's bounding box and the bottom of the
screen remains at 30px.

Pay attention! The alignment distance provided by the Widget component refers to the
border of the bounding box that is located in the same direction as the child node and parent
node. For example, Left is ticked off in the above example to align the element with the left
border, then the distance between the left border of the child node's bounding box and the
left border of the parent node's (i.e., Canvas node, whose bounding box is constantly the
same size as the screen) bounding box is the set value: 50px.

Nest alignment elements


The method of aligning with the border of the screen is introduced above. Because the
default alignment reference of Widget is the parent node, we can add different node
hierarchies and make the nodes on every hierarchy use the auto alignment function.

Next, we will use a simple example to explain it. Supposing we have a node hierarchical
relation as follows:

In the example above, parent is a panel, and button is a button. We can respectively add
Widget component to these two nodes, and respectively set their alignment distance.

For the parent node, the distance of aligning the top left corner of the Canvas node
remains at 80px:

149
Widget Align

For the button node, the distance of aligning the top left corner of the parent node
remains at 50px:

With a workflow like this, we can group UI elements according to their display areas or
functions, and elements of a different hierarchy can be aligned according to design.

Automatically zooming in/out the size of a


node according to alignment requirements
In the above example, two borders that simultaneously align on one axis in opposite
directions don't exist. If we want to make a panel that fully covers the width of the whole
screen, we can simultaneously tick off the alignment switches Left and Right :

150
Widget Align

When simultaneously ticking off the alignment switches in opposite directions, Widget
obtains the ability of modifying the Size of the node according to alignment requirements.
In the picture above, we ticked off the left and right directions and set up margins, then
Widget can dynamically set up the Width property of the node according to the width of the
parent node. As a result, no matter how wide the screen is, the distance between the panel
and the left & right borders of the screen remains at 100px permanently.

Create a node whose size is in accordance with the size of


screen
Making use of the features of a node that can automatically zoom in/out, we can make the
size of the node the same with that of the screen by setting up the Widget component of the
node. Therefore, we don't have to put all the UI elements that need to align with the borders
of screen under the Canvas node, but group them according to the requirements of function
and logic.

To make such a node, we should first make sure that the size of the parent node of this node
remains the same with that of the screen. The Canvas node is the best choice. Next, set up
the Widget component of this node according to the following method:

151
Widget Align

Therefore the size of the node will remain constantly the same with that of the Canvas node
when running, i.e., the same as the size of the screen. After being set up like this, the child
node of this node can transmit the same screen size by the same settings.

What needs to be noted is that because the Canvas node itself has the function of remaining
the same size as that of the screen, there is no need to add the Widget component to the
Canvas node.

Set up percentage alignment distance


After opening the alignment function of a certain direction on the Widget component, apart
from margins whose unit is designated as pixels, we can also input a percentage value.
Therefore, Widget will multiply the width or height of the parent node on the corresponding
axis by the input percentage to get the value of the actual margin.

Let's take a look at a real example. Take a child node that has been directly put under
Canvas as an example. We hope this node panel remains on the right side of the screen
and constantly covers 60% of the total height of screen. Therefore, setting up the Widget
component according to the following picture will realize this effect:

When inputting the margin value when opening alignment direction, Widget can use the pixel
unit together with percentage unit according to various needs. For example, input 50% on
the Left direction that needs to align with the center line of the screen and input 20px on
the Right direction that needs to align with the borders of the screen; when calculating the
position and size of the child node at last, all the margins will be positioned after being
converted to pixcel distance according to the size of the parent node.

152
Widget Align

Making use of the percentage alignment distance, we can create UI elements that can zoom
in/out infinitely according to the size of the screen. Exerting your imagination, fitting a
thousand types of Android phones with one set of resources will be a piece of cake!

153
Label Layout

Label Layout
The Label component is one of the key rendering components. You need to learn about how
to set up label layout in order to have a perfect display when the UI system adapts to various
resolutions and sets up alignment.

Alignment of labels in the bounding box


Like other rendering components, the layout of the Label component is based on the Size
of the node, i.e., the scale stipulated by the Bounding Box.

What is shown in the picture above is the display effect of labels rendered by Label in the
blue bounding box. The following properties in Label determines the position of labels in the
bounding box:

Horizontal Align : the horizontal alignment of labels in the bounding box, which can be

chosen from 3 positions: Left, Right, Center.


Vertical Align : the vertical alignment of labels in the bounding box, which can be

chosen from 3 positions: Top, Bottom, Center.

The horizontal/vertical alignment positions in the above pictures are all set as Center . You
can see labels appearing on the center of the bounding box. You can modify the two
properties above to make other combinations. Labels will appear on the four sides or four
angles of the bounding box according to the settings.

Label Size and Line Height

154
Label Layout

Font Size determines the display size of labels. Its unit is Point (it can also be called

'pound'), which is the size unit for fonts commonly used in most image editing softwares and
font editing softwares. For dynamic fonts, Font Size can be zoomed in losslessly. But the
display of bitmap fonts will be more and more vague when the set value of Font Size
exceeds the font size stipulated by the font.

Line Height determines the height occupied by each line when multiple lines of labels

display, the unit of which is also Point. The displaying of multiple lines of labels can be
carried out by using two methods:

When inputting labels in the String property, manually input ‘\r’ or ‘\n’
Open the Enable Wrap Text property, which will be introduced in detail later

Relation of label size and line height:

If the values of Font Size and Line Height are the same, labels will occupy the height
of the most part of one line.
If the value of Font Size is less than that of Line Height , space between multiple
lines of labels will be enlarged
If the value of Font Size is larger than that of Line Height , space between multiple
lines of labels will be narrowed between multiple lines of labels. Overlapping of labels
may appear.

155
Label Layout

Overflow
The Overflow property determines the array of labels in the bounding box when the content
of labels is increased.

Clamp

When in Clamp mode, labels will firstly be rendered according to the requirements of
alignment type and size, but the parts exceeding the bounding box will be concealed
(clamped).

Auto Shrink

156
Label Layout

When in auto shrink mode, if labels exceed the bounding box when being rendered
according to the original size, the size of the labels will be automatically shrunk to display all
the labels.

Attention! Auto shrink mode will not zoom in on labels to adapt to bounding box.

Resize Height

Resize height mode will make sure the bounding box of the labels fits the height of the
labels, no matter the quantity of the labels' lines. This mode is suitable for displaying
paragraphs of labels that don't have the same amount of content. An infinite amount of label
content can be displayed in the arbitrary UI field when using this mode together with the
ScrollView component.

157
Label Layout

Enable Wrap Text


The Enable Wrap Text property of the Label component can switch the auto wrap switch of
labels. When Enable Wrap Text is opened, labels will automatically wrap acccording to the
width of the bounding box without manual input of ‘\r’ or ‘\n’ when inputting labels.

Auto Wrap in Clamp Mode


When clamp mode opens auto wrap, labels will be wrapped in the allowable scale of the
bounding box in priority. Only when not all the words can be displayed after being wrapped
will clamp mode function.

The following two pictures are taken when Clamp + Enable Wrap Text are opened, the
difference of which is the different width of the bounding boxes of the labels;

When the width of the bounding box is changing from the left picture to the right picture,
labels will be continuously adjusted and wrapped, greatly changing from 2 lines to 4 lines. In
the end, the clamped display will appear due to the insufficient height of the bounding box.

Auto Wrap in Auto shrink mode


Similar to clamp mode, labels will be wrapped in priority when labels exceed the width of the
bounding box in auto shrink mode. Only when the width and length of the bounding box are
exceeded will the labels be automatically shrunk to adapt to the bounding box.

Auto Height Adaptation

158
Label Layout

In auto height adaptation mode, the 'Enable Wrap Text' property is compulsorily opened.

Enable Wrap Text of Chinese


The auto wrap behavior of Chinese is different from that of English. English is wrapped by
the unit of words. Blank space is the smallest unit of wrap adjustment. Chinese is wrapped
by the unit of characters. Every character can be wrapped alone.

Anchor point of label node


The anchor point of a label node and the alignment mode of labels in the bounding box are
two concepts that need to be differentiated. In a layout type that needs labels to enlarge the
bounding box (e.g., Resize Height ), only correct setting up of anchor points can make the
bounding box be extended to the expected direction.

For example, if you want the bounding box to extend downward, you need to set the y
property of Anchor as 1 .

Widget
Add a Widget component to the node with the Label component, then you can make various
layouts for label nodes relative to their parent nodes.

159
Label Layout

In the above picture, two Label subnodes are added to the background nodes. After
respectively adding the Widget component to them, set the Right property of the Widget
for the labels on the left side as 50% , and set the Left property of the Widget for the labels
on the right side as 60% , then the multi-column layout of labels in the picture above can be
realized.

And by setting margins on the aWidget, plus the layout type of labels, a flexible and beautiful
layout for labels can be easily realized without concrete and minor adjustments to the
bounding box.

Reference for checking components


For properties of the Label component, you can also check Label Component document.

160
UI Components

Common UI Controls
The content of this document is coming soon...

Continue on to read about Auto Layout.

161
Auto Layout

Auto Layout Container


The layout component can be mounted to any node, making the node into a container with
the auto layout function. The so-called auto layout container can automatically array the
subnodes according to certain rules and adjust the container type nodes of its own size
according to the sum total of bounding boxes of the node content.

Layout Type
Auto layout components have several basic layout types. These can be set up by the Layout
Type property, which includes the following types.

Horizontal Layout

When Layout Type is set as Horizontal , all the subnodes will automatically be arrayed
horizontally, and the width of the Layout node will be set up according to the sum total of the
subnodes' Width .Then the two Label nodes included in the picture above will automatically
be arrayed horizontally.

162
Auto Layout

In the horizontal layout type, the Layout component will not interfere with the position or
height properties of the node on the y axis. The subnode can even be put outside the
maximal height of the layout node's bounding box. If subnodes need to be aligned upward
along the y axis, you can add the Widget component to the subnodes and open the
alignment mode of the Top or Bottom.

Vertical Layout

When Layout Type is set as Vertical , all the subnodes will automatically be arrayed
vertically and the height of the Layout node will be set up according to the sum total of the
subnodes' Height .

In the vertical layout type, the Layout component will not modify the position or width
properties of the node on the x axis. Subnodes can only be neatly arrayed by adding the
Widget and opening the Left or Right alignment mode.

Node Direction
The Layout arrays' subnodes are based on the display order of subnodes in arrangement
manager and refers to the array directions set up by the Vertical Direction or Horizontal
Direction properties.

163
Auto Layout

Horizontal Direction
You can set up two directions: Left to Right or Right to Left . The former will array the
nodes from left to right according to their display order in arrangement manager; the later
will array the nodes from right to left according to their display order in arrangement
manager.

Vertical Direction
You can set up two directions: Top to Bottom or Bottom to Top . The former will array the
nodes from top to bottom according to their display order in arrangement manager; the
later will array the nodes from bottom to top according to their display order in arrangement
manager.

Other layout types are coming soon


We will update this part of the document in the next edition.

For the properties of other Layout components, please check Layout document.

164
List With Data

Create a list of dynamically generated


content
The content of this document is coming soon...

165
Animation

About Animation

Animation components and Animation clips


Cocos Creator is a componentized structure. Animation is no exception, it is a component in
the Node. Animation clips, however, are documents for saving animation data. Animation
clips need to be mounted to Animation components to enable the engine to smoothly apply
animation data to the Node.

Understanding animation editor


The Animation editor can be divided into 7 parts.

1. Common button field, which displays some common functional buttons, such as: (from
left to right) recording status switch, back to the first frame, last frame, play/stop, next
frame, create a new animation clip and insert animation event.

2. Timeline and event, which mainly displays timeline. The added user defined events will
display here too.

3. Hierarchy management(node tree), which includes node data that can be influenced by
the current animation clip.

4. The preview field of the animation frame in nodes, which mainly displays the preview
timeline of all the frames in each node.

5. Property list, which displays the property lists of the currently chosen node that has
been included in the chosen animation clip.

166
Animation

6. Key frame. The frame corresponding to each property will display here.

7. Basic properties of animation clip. After choosing the animation clip, the basic data will
display here and can be modified.

Basic operation
Modify the zoom proportion of timeline
Scroll the mouse wheel in area 2, 4, 6 of the image, and the display percentage of the
timeline can be zoomed in/out.

Modify the display area of timeline


1. Press Shift button on the keyboard, left-click area 2, 4, 6 in the image and drag it to the
left/right.

2. Press down the middle mouse button in area 2, 4, 6 in the image and drag it.

Modify the currently chosen timeline node


1. Click or drag any position in the timeline (area 2) area, you can modify the current time
node.

2. Drag the marked red line in area 4.

Open/close recording status


1. There is a red button on the left side of graph 1. Click it and you will open/close the
recording status.

2. The adding and deletion of the property frame and path will automatically open the
recording status.

3. The playing of the animation will automatically open the recording status.

4. When playing, operations like saving the scene, etc., will close the recording status.

Play/stop animation
1. Click the Play button in graph 1, which will automatically turn into Stop. Click the button
again and the animation will be stopped.

167
Animation

2. When playing, operations like saving the scene, etc. will stop playing.

168
Animation Clip

Creating Animation components and


animation clips

Creating an Animation component


We can add different components to each Node. If you want to create an animation on a
Node, we must create a new Animation component for it.

There are 2 methods for creating an animation:

1.Choose the Node that you want to use. Click + on the top right corner or Add component
below in the property checker and choose Animation in “other components”.

1. Open the animation editor. Choose the Node that you want to add the animation to in
the arrangement manager. Click the Add Animation component button.

Create and mount animation clips


We have an Animation component on the Node, but we don't have the corresponding
Animation clip data. There are 2 methods for creating an Animation clip:

1. Click + on the top left corner in the resource manager or right click in the blank area and
choose Animation Clip. A clip document named 'New AnimationClip' will be created.

Creating it is not enough. You need to click and choose the Node in the arrangement
manager again and find Animation in the property checker. The current value of Clips will
be 0. Change it to 1.

169
Animation Clip

Drag the newly created 'New AnimationClip' from the resource manager into the newly
emerged animation-clip choice box.

1. If the Animation component hasn't been added to any Animation clip documents, you
can click the Create an Animation Clip button in the animation editor to create a new
Animation clip document from the pop up window.

You need to pay attention! If you choose to cover the existing clip document, the contents of
the covered document will be erased.

170
Animation Curve

Editing an Animation curve


Now, that you have mounted Animation clips to the Node, you can create Animation curves
in your Animation clips.

First, you need to understand Animation properties. These include the existing properties of
the Node, such as, position rotation, etc. and the user-defined properties of the component.
Properties that are included in a component will add the name of the component to the
beginning of their own name, such as: cc.Sprite.spriteFrame .

For example, in the image above, the position curve is the property path and the
corresponding blue dots are animation frames.

Adding a new property path


The normal method for adding a new property path involves first choosing the Node and
then clicking add property in the property field. In the pop up menu, all of the addable
properties will be listed. Choose the property that you want to add and a corresponding path
will be added.

You can also directly modify the corresponding properties of the Node in the recording
status. Open the recording status, by clicking the red circle in the top left corner and directly
drag the chosen Node into the scene editor and an add property path will correspondingly
be added to the property list and a key frame will be added to the current timeline. Also, in
the recording status, direct modifications of other properties in the property checker will
automatically add the property path and key frame.

171
Animation Curve

Delete a property path


Right click the property in the property list and choose the delete option in the pop up menu
and the property will be deleted from the animation data.

Add an animation frame


Direct modifications of properties in recording status can automatically add corresponding
properties and frames.

You can also directly click the ??sign on the right side of the corresponding property in the
property list, then a frame will be added to the currently selected point in time.

Choose an animation frame


Click the created sequence frame and it will be displayed in the selected state. Now the
sequence frame will turn from blue to white. If you need to select multiple sequence frames
at once, you can hold down the Ctrl key and select the ones you need or directly drag and
highlight them in the property field.

172
Animation Curve

Move an animation frame


If you move the mouse to any randomly chosen Node, the mouse will display left and right
arrows. You can drag all the chosen Nodes while holding down the left mouse button.

Modify an animation frame


Click the animation frame that needs to be modified and the selected frame on the timeline
will jump to this frame. After making sure the recording status is opened, you can directly
modify the corresponding properties in the property checker.

Delete an animation frame


After choosing a sequence frame, click the ??sign in the property field and the currently
selected sequence frame will be deleted. Or directly press the Delete key on the keyboard
and all the selected nodes will be deleted.

173
Sprite Animation

Editing Sprite animation


Let's see a concrete method for creating a frame animation.

Add a new Sprite component to node


First, we need to make the Node properly displays textures. To do this we need to add a
Sprite component to the Node. After selecting the Node, choose add render component-
>Sprite by clicking the Add component button in the property checker.

Add a cc.Sprite.spriteFrame to property list


Once the Node is able to properly display textures, we need to create an animation path for
the texture. Click add property in the animation editor, then choose cc.Sprite.spriteFrame

Add a frame
Drag the texture from the resource manager to the property frame field and put it on the
cc.Sprite.spriteFrame path. Then drag the texture that needs to be displayed in the next

frame to the designated position. Click Play and the newly created animation can be
previewed.

Continue on to read Time Curves.

174
Time Curve

Editing a time curve


We have already created some basic animations. However, sometimes we need to use
slow-motion effects like EaseInOut, etc., between two frames. So how can this be achieved
in the animation editor?

First, we need to create two unequal frames on one path. For example, create two frames
on a position which starts from 0,0 to 100,100, then a connecting line between these two
frames will appear. Double click the connecting line and the time curve editor will open.

Using a pre-set curve


We can select various pre-set effects from the left-hand side of the curve editor, such as:
Ease In, etc. After selecting, some pre-set parameters will appear at the top on the right-
hand side. These can be chosen according to your needs.

A user-defined curve
Sometimes the pre-set curve cannot meet the needs of the animation. However, we can
modify the curve ourselves. In the preview image in the bottom right, there are two grey
controlling points. By dragging these controlling points, the path of the curve can be

175
Time Curve

modified. If the controlling points need to be dragged outside of the visual field, you can use
the mouse wheel or small plotting scale on the top right corner to zoom in/out of the preview
image. The proportions supported by which range from 0.1 to 1.

Continue on to read Animation Events.

176
Animation Event

Animation Events.
When using animations in your games, you may want things to during a frame or even at the
end of a frame. We call these animation events.

Adding an event
First, choose the position where you want an event to happen. Click the add event button at
the far left side of the button field. A white rectangle will appear on the timeline representing
the newly added event.

Deleting an event
There are two ways to delete and event.

Double click the white rectangle that represents the event.


Click the Recycle icon behind Function after opening the event editor. A prompt for
deleting this event will appear. Click the Confirm button and the event will be deleted.

177
Animation Event

You can also right click Event in the animation editor and choose Delete.

Specifying the event trigger function and


import parameters
Double click the white rectangle of the event you want to modify and the event editor will
open. In the editor, you can manually input the function name that needs to be transmitted.
When triggering, the corresponding method will be matched to each component according to
this function name.

If you want add imported parameters, you can click ??or ??near Params. Only three types of
parameters supported: Boolean, String and Number.

178
Scripting Animation

Using scripts to control animation

Animation component
Animation components provide some common animation control functions. If you only need
simple animation control, you can do some operations by obtaining the Animation
component of the Node.

Play

var anim = this.getComopnent(cc.Animation);

// if no animation is designated to play and defaultClip is set up, play defaultClip a


nimation
anim.play();

// designate test animation to play


anim.play('test');

// designate test animation to play from 1 second


anim.play('test', 1);

When playing an animation, Animation will evaluate the former playing state of the animation
for next step operation. If animation is in:

Stop state, then Animation will directly re-play this animation


Pause state, then Animation will resume the playing of the animation and continue
playing it from the current time
Play state, then Animation will stop this animation and re-play it

var anim = this.getComopnent(cc.Animation);

// play the first animation


anim.play('position-anim');

// play the second animation


anim.play('rotation-anim');

Animation supports playing multiple animations simultaneously. The playing of different


animations will not influence the playing state of each other, which is helpful for the creation
of some complex animations.

179
Scripting Animation

Pause Resume Stop

var anim = this.getComopnent(cc.Animation);

anim.play('test');

// designate test animation to pause


anim.pause('test');

// pause all the animations


// anim.pause();

// designate test animation to resume


anim.resume('test');

// resume all the animations


// anim.resume();

// designate test animation to stop


anim.stop('test');

// stop all the animations


// anim.stop();

Invoking Pause, Resume and Stop functions is similar.

Pause will temporarily stop playing the animation. Resume, the animation will continue
playing from the current time. However, Stop will stop the playing of the animation. When
being played again, this animation will start playing from the beginning.

set up the current time of animation

var anim = this.getComopnent(cc.Animation);

anim.play('test');

// set the current playing time of test animation as 1 second


anim.setCurrentTime(1, 'test');

// set the current playing time of all animations as 1 second


// anim.setCurrentTime(1);

You can set the current time of animation at anytime. But, the status of the animation will not
be immediately modified according to set time. Only in next update of the animation will the
playing status be re-calculated according to this time.

180
Scripting Animation

AnimationState
Animation only provides some simple control functions. For more animation informations
and controls, AnimationState is needed.

What is AnimationState?
If AnimationClip is the carrier of animation data, then AnimationState is the concrete
example of running AnimationClip, which decodes animation data into numeric values that
are convenient to be calculated by program. When Animation is playing an AnimationClip,
AnimationClip will be docoded into AnimationState. The playing state of Animation is
actually calculated by AnimationState, which includes whether animation will loop or not,
how to loop, playing speed, etc..

obtain AnimationState

var anim = this.getComopnent(cc.Animation);


// play will return associated AnimationState
var animState = anim.play('test');

// or directly obtain
var animState = anim.getAnimationState('test');

Obtain animation information

181
Scripting Animation

var anim = this.getComopnent(cc.Animation);


var animState = anim.play('test');

// obtain clip associated with animation


var clip = animState.clip;

// obtain animation name


var name = animState.name;

// obtain the playing speed of animation


var speed = animState.speed;

// obtain the total duration of animation


var duration = animState.duration;

// obtain the playing time of animation


var time = animState.time;

// obtain the repeat count of animation


var repeatCount = animState.repeatCount;

// obtain the loop mode of animation


var wrapMode = animState.wrapMode

// obtain if the animation is playing


var playing = animState.isPlaying;

// obtain if the animation is paused


var paused = animState.isPaused;

// obtain the frame rate of animation


var frameRate = animState.frameRate;

From AnimationState, all the animation information can be obtained. You can use this
information to see what should be done.

Set up the playing speed of animation

var anim = this.getComopnent(cc.Animation);


var animState = anim.play('test');

// accelerate the playing speed of animation


animState.speed = 2;

// slow down the playing speed of animation


animState.speed = 0.5;

The greater the speed value is, the faster the speed is, and vice versa

182
Scripting Animation

Set up the loop mode and loop count of animation

var anim = this.getComopnent(cc.Animation);


var animState = anim.play('test');

// set the loop mode as Normal


animState.wrapeMode = cc.WrapMode.Normal;

// set the loop mode as Loop


animState.wrapeMode = cc.WrapMode.Loop;

// set the loop count of animation as 2 times


animState.repeatCount = 2;

// set the loop count of animation as infinite


animState.repeatCount = Infinity;

AnimationState permits the dynamic setting up of loop mode. Currently, various loop
modes are provided. These loop modes can be obtained from cc.WrapMode. If the loop
category of animation is Loop category, it should be used together with repeatCount to
achieve this effect. By default, when decoding animation clips, if the loop category of
animation is:

Loop category, repeatCount will be set as Infinity, i.e., infinite loop


Normal category, repeatCount will be set as 1

Animation event
Visually editing the frame event is supported in the animation editor (For the methods of
editing, please refer to Animation event). Writing the callback of the animation event in the
script is very simple too. The callback of the animation event is actually a normal function.
The frame event added to the animation editor will map onto the component of animation
root node.

Concrete example:

183
Scripting Animation

Suppose a frame event is added to the end of animation, which is as illustrated below:

Then in the script, you can write like this:

cc.Class({
extends: cc.Component,

onAnimCompleted: function (num, string) {


console.log('onAnimCompleted: param1[%s], param2[%s]', num, string);
}
});

Add the above components to the root node of animation. When animation is about to end,
animation system will automatically invoke onAnimCompleted function in the script. Animation
system will search in all the components of animation root node. If there is a function that
designated to realize animation event in components, then it will be invoked and parameters
written in the event will be imported.

184
Sprite

Sprite component reference


Using Sprites is the most common way to display images in a 2D game. By adding the
Sprite component to a node you can display images from the project resources within the
scene.

Click the Add Component button at the bottom of the Inspector and select Sprite from
Add Rendering Component to add the Sprite component to the node.

Sprite attribute
Attribute Function Explanation
Atlas Atlas resource which the Sprite display image resource belongs to.
Sprite Frame SpriteFrame image resource which is used to render the Sprite.
Rendering mode, currently includes Simple and Sliced rendering
Type
modes.

Use Original Whether to use the original size of the image resource as the Sprite
Size node size.

Detailed explanation
After adding the Sprite component, drag the Texture or SpriteFrame type resource from the
resource manager to the Sprite Frame attribute reference. The resource image can then
be displayed through the Sprite component.

If this SpriteFrame resource is contained within an Atlas resource, then the Atlas attribute
of the Sprite will be set up along with it. Later you can click the choose button next to the
Atlas attribute to choose another SpriteFrame from this Atlas to assign to the Sprite.

185
Sprite

Rendering mode
Currently, the Sprite component supports two rendering modes:

Simple mode: rendering the Sprite according to the original image resource. It is
normally used along with Use Original Size to guarantee the image shown in the
scene is in full accordance with the image designed by the graphic designer.
Sliced mode: the image is cut up into a nine square grid and according to certain rules
is scaled to fit freely set dimensions ( size ). It is usually used in UI elements or to
make images that can be enlarged infinitely without influencing the image quality into
images cut up into a grid to save game resource space. Please read use Sprite editor to
make a Sudoku image for detailed information.

186
Label

Label component reference


The Label component is used to show a piece of text in the system font, TrueType font or
BMFont. Label also has a composing function.

Click the Add Component button at the bottom of the Inspector and select Label from
Add Rendering Component to add the Label component to the node.

Label attribute

187
Label

Attribute Function Explanation

String Text content character string.


Horizontal Horizontal alignment pattern of the text. The options are LEFT, CENTER
Align and RIGHT.
Vertical Vertical alignment pattern of the text. The options are TOP, CENTER and
Align BOTTOM.

Font Size Font size of the text.


Line
Line height of the text.
Height
Layout pattern of the text. Currently supports CLAMP, SHRINK and
Overflow
RESIZE_HEIGHT. See Label Layout for more detailed information.

Enable
Enable or disable the text line feed.
Wrap Text
Designate the font file needed for rendering the text. If the system font is
File
used, then this attribute can be set to null.
Use
System Boolean value, choose whether to use the system font or not.
Font

Label Layout
Attribute Function Explanation
The text size won't zoom in or out as the Bounding Box size
changes. When Wrap Text is disabled, parts exceeding the
Bounding Box won't be shown according to the normal character
CLAMP
layout. When Wrap Text is enabled, it will try to wrap the text
exceeding the boundaries to the next line. If the vertical space is
not enough, any not completely visible text will also be hidden.
The text size will zoom in or out (it won't zoom out automatically,
the maximum size that will show is specified by Font Size) as the
Bounding Box size changes. When Wrap Text is enabled, if the
width is not enough, it will try to wrap the text to the next line
SHRINK
before automatically adapting the Bounding Box's size to make the
text show completely. If Wrap Text is disabled, then it will compose
according to the current text and zoom automatically if it exceeds
the boundaries.

The text Bounding Box will adapt to the layout of the text. The user
RESIZE_HEIGHT cannot manually change the height of text in this status; it is
automatically calculated by the internal algorithm.

188
Label

Detailed explanation
By dragging the TTF font file and BMFont font file into the file attribute in the Inspector
the Label component can alter the rendering font type. If you want to stop using a font file,
you can use the system font again by checking Use System Font ?

---`

Continue on to read about Animation component reference.

189
Animation

Animation component reference


The Animation component enables a node and its child node to make an animation.

Click the add component at the bottom of Inspector and select Animation from add other
components in order to add the Animation component to the node.

Animation attribute
Attribute Function explanation

Default animation editing. If you set the value for this as one and Play On
Default
Load as true, then the animation will play the contents of Default Clip
Clip
automatically after loading.
Default list type is null. If you add an AnimationClip in here, then it will be
Clips mirrored in the animation editor; users can edit the contents of Clips in
the animation editor

Play On Boolean type. Chooses whether to play the content of the Default Clip
Load automatically after the animation loads.

Detailed description
If we need to have many nodes contained in one animation, then normally we will create a
new node as the root node of the animation and add the Animation component to this root
node. The other child nodes of the root node will then automatically enter this animation.

190
Animation

If the following node tree is added:

Then the hierarchy in the animation editor will show:

For more information aboutAnimation, please read animation system.

191
Canvas

Canvas component reference


The Canvas component can get the actual resolution of the device screen and zoom in and
out of all the rendered elements in the scene. There can only exist one Canvas component
in the scene at a time. We recommend you set all the UI and renderable elements as
Canvas' child nodes.

Options
Options Explanation
Design Design resolution (the resolution blueprint used while the content
Resolution producer builds the scene)
Auto-fit height (the height of the design resolution will auto-fit to the
Fit Height
screen height)

Auto-fit width (the width of the design resolution will auto-fit to the
Fit Width
screen width)

Continue on to read about the Widget component reference.

192
Widget

Widget component reference


Widget is a frequently used UI layout component. It can make the current node automatically
align to an optional position of the parent object or restrict dimensions to make your game
adaptive to different resolution ratios.

Options
Options Explanation Note

Upper After selecting, an input field will appear to set the


Top border distance between the upper border of the current
alignment node and the upper border of the parent object.
Lower After selecting, an input field will appear to set the
Bottom border distance between the lower border of the current
alignment node and the lower border of the parent object.

After selecting, an input field will appear to set the


Left border
Left distance between the left border of the current
alignment
node and the left border of the parent object.
After selecting, an input field will appear to set the
Right border
Right distance between the right border of the current
alignment
node and the right border of the parent object.

Horizontal
HorizontalCenter center
alignment
Vertical
VerticalCenter center
alignment

193
Widget

Border alignment
We can place a Widget below Canvas, and perform the following tests:

Left alignment, left border distance 100 px:

Bottom alignment, left border distance 50%:


The percentage will take the width or height of the parent object as a benchmark

Bottom right alignment, border distance 0 px:

194
Widget

Center alignment
Horizontal center alignment:

Vertical center alignment and right border distance 50%:

195
Widget

Limit size
If you align the left and right side at the same time, or align the top and bottom at the same
time, then the size will be stretched in the corresponding direction. Let us look at a
demonstration. Place two rectangular Sprites in the scene and take the bigger one as the
dialog box background and the smaller one as the button on the dialog box. Take the button
node as the child node of the dialog box and set the button into Sliced mode so that you can
observe the stretch effect.

Horizontal stretch, left and right margin 10%:

196
Widget

Vertical stretch, no margins on each end and horizontal


center alignment:

Stretch in the horizontal and vertical directions, margin 50


px:

197
Progress

ProgressBar component reference


ProgressBar is usually used to show the progress of a certain operation in the game. Add
the ProgressBar component to a node and associate a Bar Sprite to this component. The
Bar Sprite can then be controlled to show progress in the scene.

Click the add component button at the bottom of the Inspector and select ProgressBar from
add UI component ? You can then add the ProgressBar component to the node.

ProgressBar attribute
Attribute Function Explanation

Bar The Sprite component needed for rendering ProgressBar. It can be linked
Sprite by dragging a node with the Sprite component to this attribute.
Currently supports the horizontal and vertical modes. The initial direction
Mode
can be changed by cooperating with the Reverse attribute.

Total The total length/total width of the Bar Sprite when the ProgressBar is at
Length 100%.
Progress Floating point. The data range is 0~1; values beyond that are not allowed.

Boolean value. The default filling direction is from left to right/bottom to top.
Reverse
You can switch between the two after it has been opened.

198
Progress

Detailed explanation
After adding the ProgressBar component, drag a node with the Sprite component from the
Hierarchy to the Bar Sprite attribute. You can then control the display of the ProgressBar by
dragging the progress sliding block.

Bar Sprite could be its own node, child node or any node that comes with the Sprite
component. Also, Bar Sprite can freely choose the Simple or Sliced rendering modes.

199
Button

Button component reference


The button component responds to a click from the user. When the user clicks a Button, its
status will change. In addition, users can assign a custom behavior to buttons' click event.

Click the ‘add component’ button at the bottom of the Inspector and select ‘Button’ from
‘add UI component’. You can then add the Button component to the node.

Button attribute

200
Button

Attribute Function explanation

Boolean type, if set to false then the Button component enters the
Interactable
forbidden state.
Enumeration type, including NONE, COLOR and SPRITE. Each type
Transition corresponds to a different Transition setting. Please check more detailed
information in the chapter ‘Button Transition’.
Default list type is null. Each event added by the user is composed of the
Click Event node reference, component name and a response function. Please
check more detailed information in the chapter ‘Button Event’.

Button Transition
Button Transition is used to indicate the status of the Button when clicked by the user.
Currently the types available are NONE, COLOR and SPRITE.

Color Transition

Attribute Function Explanation

Normal Color of Button under Normal status.


Pressed Color of Button under Pressed status.

Hover Color of Button under Hover status.


Disabled Color of Button under Disabled status.

Duration Time interval needed for Button status switching.

Sprite Transition

201
Button

Attribute Function Explanation

Normal SpriteFrame of Button under Normal status.


Pressed SpriteFrame of Button under Pressed status.

Hover SpriteFrame of Button under Hover status.


Disabled SpriteFrame of Button under Disabled status.

Button event

Attribute Function Explanation


Target Node with the script component.
Component Script component name.

Assign a call-back function which will be triggered when the user clicks
Handler
and releases the Button.

Detailed explanation
Button currently only supports the On Click event. This means only when users click and
release the Button will the corresponding call-back function be triggered.

202
Mask

Mask component reference


Mask is used to specify the range where the child node can perform rendering. Nodes with a
component that contains Mask will use a bounding box (which has the range specified by 憇
ize? of this node to create a rendered mask. All of the child nodes of this node will clip
according to this mask and the area outside the mask won't be rendered.

Click the add component button at the bottom of the Inspector and select Task from add
rendering component ? You can then add the Mask component to the node.

Mask attribute
Attribute Function Explanation

NA NA

Detailed explanation
After adding the Mask component to a node, all the child nodes of this node will be affected
by Mask during rendering.

203
Scrollview

ScrollView component reference


ScrollView is a container with a scroll function. It provides a way to browse more contents
within a limited display area. Generally, ScrollView will be used along with the Task
component and the ScrollBar component can also be added to show the location of the
browsing content.

Click the add component button at the bottom of the Inspector and select ScrollView from
add UI component You can then add the ScrollView component to the node.

ScrollView attribute

204
Scrollview

Attribute Function Explanation

A reference node for creating scrollable content from ScrollView. It could


Content
be a node containing a very large picture.
Horizontal Boolean value, whether horizontal scroll is allowed or not.
Vertical Boolean value, whether vertical scroll is allowed or not.

Inertia Is there an accelerating velocity when scrolling?


Floating point number, the deceleration coefficient after scrolling. The
Brake value range is 0-1 where if set to 1, then the scroll will stop immediately; if
set to 0, then the scroll will continue until the content border.
Elastic Boolean value, whether to bounce back or not.

Bounce Floating point number, the time duration for bounce back. The calue range
Duration is 0-10.
Horizontal A reference node for creating a scroll bar showing the horizontal position
ScrollBar of the contents.
Vertical A reference node for creating a scroll bar showing vertical position of the
ScrollBar contents.

Detailed explanation
The ScrollView component can only work with the specified content node. It calculates
location information during scrolling using both the designated scroll direction and the length
of the content node in this direction. The content node can also set to auto resize through
the UI Widget ?

Normally a ScrollView node tree resembles the following:

Here, the Viewport is used to define a scroll area that can be displayed. As a result, the
Mask component will normally be added to the Viewport. Contents that can scroll can be put
in the content node or added to its child node.

ScrollBar settings

205
Scrollview

ScrollBar is optional. You can choose to set either a horizontal or vertical ScrollBar or of
course set them both.

To build a connection, you can drag a node with the ScrollBar component in the Hierarchy
over to the corresponding field in ScrollView.

206
Scrollbar

ScrollBar component reference


ScrollBar allows the user to scroll a picture (not currently supported in the public beta
version) by dragging a sliding block. It's a bit similar to the ‘Slider’ component, but it is mostly
used for scrolling while Slider is used to set values.

Click the ‘add component’ button at the bottom of the Inspector and select ‘ScrollBar’ from
‘add UI component’. You can then add the ScrollBar component to the node.

ScrollBar attribute
Attribute Function Explanation
ScrollBar foreground picture. Its length/width will be calculated according to
Handle the content size of ScrollView and the dimensions of the actual display
area.
Direction Scroll direction. You can currently select from either horizontal or vertical.
Enable
Enable or disable auto hide. If it is enabled, then ‘Auto Hide Time’ will hide
Auto
automatically after the ScrollBar is shown.
Hide

Auto
Hide Auto hide time; need to set Enable Auto Hide along with it.
Time

Detailed explanation
ScrollBar normally is used together with ‘ScrollView’ instead of being used alone. Also,
ScrollBar needs to assign a ‘Sprite’ component, i.e. ‘Handle’ in the attribute panel.

Normally we will also designate a background picture to ScrollBar. This can be used to
indicate the length or width of the whole of the ScrollBar.

207
Scrollbar

208
Layout

Layout component reference


Layout is a container component. The container can unlock the auto-layout function to
automatically arrange all the sub-objects according to the specifications so that the user can
use it to make list, page turning and other functions conveniently.

Click add component button at the bottom of Inspector and then select Layout from add UI
component , then you add the Layout component to the node.

Layout attribute

209
Layout

Attribute Function Explanation

Layout
Layout type, currently has NONE, HORIZONTAL and VERTICAL.
Type
Auto Read only attribute, indicates the current layout container will auto adapt
Resize its own size to the number and size of the sub-object.
The space between the sub-object and the container frame in the layout.
Margin
NONE mode doesn't have this attribute.
The separation distance between sub-objects in the horizontal layout.
SpacingX
NONE mode doesn't have this attribute.

The separation distance between sub-objects in the vertical layout.NONE


SpacingY
mode doesn't have this attribute.
When it is designated as horizontal layout, which side does the first child
Horizontal
node start in the layout? The left or the right? Show this attribute only
Direction
when the Layout Type is HORIZONTAL.

When it is designated as vertical layout, which side does the first child
Vertical
node start in the layout? The upside or the downside? Show this attribute
Direction
only when the Layout Type is VERTICAL.

Detailed explanation
The default layout type is NONE after adding the Layout component. It indicates that the
container won't change size and location of the sub-object. When the user places sub-object
manually, the container will take the minimum rectangular region that can contain all the sub-
objects as its own size.

You can switch the layout container type by altering Layout Type in Inspector, all the layout
types currently only support Auto Resize of the container itself.

210
Use Component

Creating and using component script

Creating component script


In Cocos Creator, script is also a part of the asset. You can add and select JavaScript or
CoffeeScript to create a component script by clicking the "create" button in the asset editor.
By this time, you will get a new script in your asset editor:

A simple component script is as follows:

cc.Class({
extends: cc.Component,

properties: {
},

// use this for initialization


onLoad: function () {
},

// called every frame, uncomment this function to activate update callback


update: function (dt) {
},
});

211
Use Component

Editing script
Cocos Creator has installed a lightweight Code Editor for editors to edit script fast. Users
can also choose their preferred text tool (such as Vim, Sublime Text, Web Storm, Visual
Studio...) to edit script according to their own need.

By double clicking the script asset, users can open the built-in Code Editor to edit. If you
need to use the external tools, the first thing you need to do is to locate the asset catalog in
the file system, then edit it with the help of its own text tool.

Edit the script and save it, and Cocos Creator will automatically detect the alteration of the
script and compile it quickly.

Adding script into the scene node


Adding the script into the scene node is actually adding a component to this node. Let's
rename the new “NewScript.js” to “say-hello.js”. Then select the scene node you would like
to add, by this time the property of this node will be shown in Inspector. There's an "add
component" button at the very bottom of Inspector. Click the button and choose: add user
script -> say-hello to add a new script component.

If everything goes well, you will see your script shown in Inspector :

212
Use Component

Note: You can also add script by dragging script asset into Inspector.

213
Properties

attribute declaration
By employing attribute declaration in the component script, we can visually show the field of
the script component in Inspector so that we can adjust the attribute value in the scene
easily.

To declare the attribute, all you need to do is put the attribute name and parameters in the
cc.Class defining properties field, for instance:

cc.Class({
extends: cc.Component,
properties: {
userID: 20,
userName: 'Foobar'
}
});

At this time, you can see in Inspector the two properties you just defined are shown in the
inspector panel:

Declaration method
In Cocos Creator, we provide two kinds of attribute declaration methods:

Simple declaration
In most cases, we can use simple declaration. When the attribute declared is the Javascript
built-in type boolean , string and number , it can be written directly into:

properties: {
foo: 20,
bar: 'Hello World!',
foobar: false,
}

214
Properties

When the delared attribute type is inherited from cc.ValueType ( such as


cc.Vec2 , cc.Color , cc.Size etc.), then it can be assigned with an example, such as:

properties: {
foo: new cc.Vec2(10,20),
bar: new cc.Color(255, 255, 255, 128),
}

When the delared attribute type is inherited from cc.Class (such as


cc.Node , cc.Component etc.), you can finish the declaration by writing its constructor in

the delaration, such as:

properties: {
foo: cc.Node,
bar: cc.Sprite,
}

Note: Other than the situations above, we all need to use complete declaration to write for
other types (such as array).

Complete declaration
Under some circumstances, we need to add parameters for the attribute declaration. These
parameters control the attribute display mode in Inspector , and the attribute behavior in the
serial scene process. For example:

properties: {
score: {
default: 0,
displayName: 'Score (player)',
tooltip: 'The score of player',
}
}

The code above stipulates that the attribute name of the score in Inspector will be shown as
“Score (player)”, and when the cursor moves on to the parameter, it will show the
corresponding Tooltip.

Below are the general parameters. For detailed usage please refer toattribute parameter.

default: set default value for attribute


type: restrict data type of attribute
visible: the attribute is invisible in the Inspector panel if set to false
serializable: do not serialize this attribute if set to false

215
Properties

displayName: display the assigned name on the Inspector panel


tooltip: add Tooltip of attribute in the Inspector panel

Declaration method for special type


Array declaration
The default of array must be set to [] , if you are about to edit in Inspector, then you also
need to set the type into constructor, enumeration, or 'Integer' , 'Float' , 'Boolean' and
'String' .

properties: {
names: {
default: [],
type: ['String']
},

enemies: {
default: [],
type: [cc.Node]
},
}

get/set declaration
After setting get or set in the attribute, when you access the attribute, the pre-defined get or
set method will be triggered. Defining the method is as follows:

properties: {
width: {
get: function () {
return this._width;
},
set: function (value) {
this._width = value;
}
}
}

Note: You can define the get method only, so this is like one attribute of read only.

For more attribute parameters, please read attribute parameter.

216
Properties

217
Access Node Component

Access node and other component


You can edit node and component in the Properties panel, or dynamically modify in script
as well. The advantage of dynamic modification is let you modify or transit property
continuously for a period of time, to achieve some easing effects. Script can also be used to
respond player inputs, or modify-create-or-destroy node and component, so as to implement
various game logics. To achieve these, you should acquire the node or component which
you want to modify.

In this tutorial, we will introduce how to

get the node which a component belongs to


get other component
setup node and component in Properties panel
find child node
find node in global
access exists variable

Get the node which the component belong


Getting the node which the component belong is easy, just use this.node variable in
component:

start: function () {
var node = this.node;
node.x = 100;
}

Get other component


You will get other component in the same node frequently, that is where getComponent
comes in, it help you to find the component you need.

218
Access Node Component

start: function () {
var label = this.getComponent(cc.Label);
var text = this.name + ' started';

// Change the text in Label Component


label.string = text;
}

You can also pass in a class name for the getComponent . For user defined components, the
class name is simply the filename of the script, and case sensitive. For example, if a
component declared in "SinRotate.js", its class name will be "SinRotate".

var label = this.getComponent("cc.Label");

There is also a getComponent method on node, they are the same thing.

start: function () {
cc.log( this.node.getComponent(cc.Label) === this.getComponent(cc.Label) ); /
/ true
}

If the component is not exists in the node, getComponent will return null. If you are trying to
access a null value at runtime, the "TypeError" exception will be thrown. So always
remember to check if you are not sure of it.

start: function () {
var label = this.getComponent(cc.Label);
if (label) {
label.string = "Hello";
}
else {
cc.error("Something wrong?");
}
}

Get other node and their component


It is not enough to access to components in the same node, scripts often need to interact
between nodes. For example, a cannon which takes aim at player by itself, need to
constantly get player's position. Cocos Creator provider some different ways to retrieve other
node and their component.

219
Access Node Component

Use Properties panel to link node


The most obvious and straightforward is to set object in Properties panel. Take node as an
example, it just need to declare a property which type is cc.Node :

// Cannon.js

cc.Class({
extends: cc.Component,
properties: {
// declare player property
player: {
default: null,
type: cc.Node
}
}
});

Above code declared a property named player in properties , its default value is null, its
object type is cc.Node . It is the equivalent of the public cc.Node player = null; statement
in other programe language. In Properties panel, the component will looks like this after the
script compiled:

Then you can drag and drop any node from Node Tree panel to the Player control:

This way, the player property will be set successfully, you can access it in your script directly:

220
Access Node Component

// Cannon.js

var Player = require("Player");

cc.Class({
extends: cc.Component,
properties: {
// declare player property
player: {
default: null,
type: cc.Node
}
},

start: function () {
var playerComp = this.player.getComponent(Player);
this.checkPlayer(playerComp);
},

// ...
});

Use Properties panel to link component


In the example above, if you set the property's type to Player component, when you drag the
"Player Node" to Properties panel, player property will be set to the Player component in
the node. Then you don't need to call getComponent for yourself.

// Cannon.js

var Player = require("Player");

cc.Class({
extends: cc.Component,
properties: {
// declare player property, but directly use component type this time
player: {
default: null,
type: Player
}
},

start: function () {
var playerComp = this.player;
this.checkPlayer(playerComp);
},

// ...
});

221
Access Node Component

You can also set the property's default value from null to an array [] , then you can set
multiple objects in Properties panel.
But if you need to dynamically get other objects in runtime, you need to search them by
using methods shown below.

Find child node


Sometimes there will be many objects with the same type in game scene, such as turret,
enemy and effects, they can be uniformly managed by a global script. If we use Properties
panel to associate them with the script one by one, that will be a heavy workload. It is often
better to manage these objects by making them all children of one parent node, then retreive
all children via the parent node:

// CannonManager.js

cc.Class({
extends: cc.Component,

start: function () {
this.cannons = [];
this.cannons = this.node.getChildren();
}
});

The getChildren is the cc.Node 's built-in API which returns all children in an array.

You can also use getChildByName :

this.node.getChildByName("Cannon 01");

If the child's hierarchy is too deep, you can use cc.find , cc.find will find step by step
based on the path passed into it:

cc.find("Cannon 01/Barrel/SFX", this.node);

Find by name globally


When omit the second parameter of cc.find , it will find starts from the scene root:

this.backNode = cc.find("Canvas/Menu/Back");

222
Access Node Component

Access value from exists variable


If you already have the reference of a node or component in somewhere, you can also
access them directly, there are two ways:

Access by using global variable


You should use global variable with care and understanding, we do not recommend
using it, you had better keep them readonly if really need to do that.

Let's define a global object window.Global , it will cantain two properties, backNode and
backLabel .

// Globals.js, this file can have any name

window.Global = {
backNode: null,
backLabel: null,
};

Because all scripts are declared as "use strict" by default, so you should not omit the
window. when declaring global variable.

Then you can directly initialize the Global where appropriate:

// Back.js

cc.Class({
extends: cc.Component,

onLoad: function () {
Global.backNode = this.node;
Global.backLabel = this.getComponent(cc.Label);
}
});

After initialization, you can read the value from Global in everywhere:

223
Access Node Component

// AnyScript.js

cc.Class({
extends: cc.Component,

// start will be executed after onLoad, so the Global will be initialized


start: function () {
var text = 'Back';
Global.backLabel.string = text;
}
});

An exception will be thrown if the global variable is not yet declared when you access to
it.
Please avoid name duplication with exists global variables in the system.
You must make ensure all global variable are initialized before using.

Access by using module


If you don't want to use global variable, you can use require to perform operation cross-
scirpts, let's look at an example:

// Global.js, now the filename matters

module.exports = {
backNode: null,
backLabel: null,
};

You can use require + filename(without paths) everywhere to retreive the object exported
by "export" from other scripts.

// Back.js

// this feels more safe since you know where the object comes from
var Global = require("Global");

cc.Class({
extends: cc.Component,

onLoad: function () {
Global.backNode = this.node;
Global.backLabel = this.getComponent(cc.Label);
}
});

224
Access Node Component

// AnyScript.js

// this feels more safe since you know where the object comes from
var Global = require("Global");

cc.Class({
extends: cc.Component,

// start will be executed after onLoad, so the Global will be initialized


start: function () {
var text = "Back";
Global.backLabel.string = text;
}
});

For details, please refer to Modular script.

225
Life Cycle Callbacks

Life cycle call-back


Cocos Creator provides the life cycle call-back function for component script. Users can
write the script in a specific period by defining a specific function call-back. Currently, the life-
cycle call-back functions provided for users are:

onLoad
start
update
lateUpdate
onDestroy
onEnable
onDisable

onLoad
In the initialization phase of the component script, we provide the onLoad call-back function.
onLoad call-back will be triggered when the scene has this component being loaded. The

onLoad phase guarantees you can get other nodes from the scene and the resource data

associated with the node. Normally, we will do some operation associated with initialization
in the onLoad phase. For example:

cc.Class({
extends: cc.Component,

properties: {
bulletSprite: cc.SpriteFrame,
gun: cc.Node,
},

onLoad: function () {
this._bulletRect = this.bulletSprite.getRect();
this.gun = cc.find('hand/weapon', this.node);
},
});

start

226
Life Cycle Callbacks

The start call-back function will be triggered before the first activation of the component,
which is before executing update for the first time. start is usually used to initialize some
intermediate state data which may have changed during update and frequently enables and
disables.

Note: When the component shifts back from a disabled state to an enabled state, start
will be called-back again.

cc.Class({
extends: cc.Component,

start: function () {
this._timer = 0.0;
},

update: function (dt) {


this._timer += dt;
if ( this._timer >= 10.0 ) {
console.log('I am done!');
this.enabled = false;
}
},
});

update
One of the key points for game development is to update an object's behavior, status and
orientation before rendering every frame. These update operations are normally put in the
update call-back.

cc.Class({
extends: cc.Component,

update: function (dt) {


this.node.setPosition( 0.0, 40.0 * dt );
}
});

lateUpdate
update will execute before all the animations' update, but if we want to perform some extra

operations after the animation update or want to perform other operations after update of
all the components are done, then we'll need the lateUpdate call-back.

227
Life Cycle Callbacks

cc.Class({
extends: cc.Component,

lateUpdate: function (dt) {


this.node.rotation = 20;
}
});

onEnable
When the enabled property of the component turns from false to true , it will trigger
onEnable call-back. If the node is created for the first time, and enabled is true , then it

will be called after onLoad but before start .

onDisable
When the enabled property of the component turns from true to false , it will activate the
onDisable call-back.

onDestroy
When the component calls destroy() , they will be collected when this frame is done. By
this time, it will call the onDestroy call-back.

228
Create Destroy

Create and destroy nodes

Create new nodes


Besides creating nodes by using the scene editor, we can create nodes dynamically in
script. Add it into the scene by new cc.Node() to complete the whole constructive process.

Below is a simple example:

cc.Class({
extends: cc.Component,

properties: {
sprite: {
default: null,
type: cc.SpriteFrame,
},
},

start: function () {
var node = new cc.Node('sprite ' + this.count);
var sp = node.addComponent(cc.Sprite);

sp.spriteFrame = this.sprite;
node.parent = this.node;
node.setPosition(0,0);
},
});

Clone the existing node


Sometimes we want to clone the existing node dynamically in the scene, it can be done by
cc.instantiate . Here is how it is done:

229
Create Destroy

cc.Class({
extends: cc.Component,

properties: {
target: {
default: null,
type: cc.Node,
},
},

start: function () {
var scene = cc.director.getScene();
var node = cc.instantiate(this.target);

node.parent = scene;
node.setPosition(0,0);
},
});

Create preset node


Like cloning the existing node, you set your prefab node and create by cc.instantiate .
Here is how it's done:

cc.Class({
extends: cc.Component,

properties: {
target: {
default: null,
type: cc.Prefab,
},
},

start: function () {
var scene = cc.director.getScene();
var node = cc.instantiate(this.target);

node.parent = scene;
node.setPosition(0,0);
},
});

Destroy node

230
Create Destroy

Nodes can be destroyed by the function node.destroy() . It's worth mentioning that node
destroying will not happen immediately, but will be executed after the logic update for the
present frame is complete. After a node is destroyed, it is in the invalid state. By
cc.isValid , the present node can be judged whether it is destroyed or not.

Here is how to use it:

cc.Class({
extends: cc.Component,

properties: {
target: cc.Node,
},

start: function () {
setTimeout(function () {
this.target.destroy();
}.bind(this), 5000);
},

update: function (dt) {


if ( !cc.isValid(this.target) ) {
this.enabled = false;
return;
}

this.target.rotation += dt * 10.0;
},
});

231
Events

Listen to and launch events

Listen to events
Even processing is done in the cc.Node . Components can register and monitor events by
visiting the node this.node . Listen to events can be registered by the function
this.node.on() . The methods are as follows:

cc.Class({
extends: cc.Component,

properties: {
},

onLoad: function () {
this.node.on('mousedown', function ( event ) {
console.log('Hello!');
});
},
});

What's worth mentioning is that the event listener function on can pass to the third
parameter target to bind the caller of the response function. The following two calling
methods have the same effect:

// bind using the function


this.node.on('mousedown', function ( event ) {
this.enabled = false;
}.bind(this));

// use the third parameter


this.node.on('mousedown', function (event) {
this.enabled = false;
}, this);

Besides listening with on , we can also use the once method. The once listener will shut
the event being listened to after the listener function responds.

Shut listener

232
Events

We can shut the corresponding event listener using off when we don't care about a
certain event anymore. One thing to note is that the parameter of off must be in one-to-
one correspondence with the parameter of on in order to shut it.

Below are what we recommend you to put in:

cc.Class({
extends: cc.Component,

_sayHello: function () {
console.log('Hello World');
},

onEnable: function () {
this.node.on('foobar', this._sayHello, this);
},

onDisable: function () {
this.node.off('foobar', this._sayHello, this);
},
});

Launch event
We can launch an event using two ways: emit and dispatchEvent . The difference
between these two is that the latter can do the event delivery. Let's get to know the emit
event through a simple example:

cc.Class({
extends: cc.Component,

onLoad: function () {
this.node.on('say-hello', function (event) {
console.log(event.detail.msg);
});
},

start: function () {
this.node.emit('say-hello', {
msg: 'Hello, this is Cocos Creator',
});
},
});

Event delivery

233
Events

Events launched by the dispatchEvent method mentioned above would enter the event
delivery stage. In Cocos Creator's event delivery system, we use bubble delivery. Bubble
delivery will pass the event from the initiating node continually on to its parent node until it
gets to the root node or is interruptedly processed by event.stopPropagation() in the
response function of some node.

As shown in the picture above, when we send the event “foobar” from node c, if both node a
and b listen to the event“foobar”, the event will pass to node b and a from c. For example:

// In the component script of node c


this.node.dispatchEvent( new cc.Event('foobar', true) );

If we want to stop the event delivery after node b intercepts the event, we can call the
function event.stopPropagation() to do this. Detailed methods are as follows:

// In the component script of node b


this.node.on('foobar', function (event) {
event.stopPropagation();
});

Event object
In the call-back of the event listener, the developer will receive an event object event of the
cc.Event type. stopPropagation is the standard API of cc.Event , other important API

include:

234
Events

API name type meaning


type String type of the event (event name)
target cc.Node primary object received by the event
current object receiving the event; current
currentTarget cc.Node object of the event in the bubble stage may
be different from the primary object
getType Funciton get the type of the event
stop the bubble stage, the event will no
stopPropagation Function
longer pass on to the parent node while the
rest of the listeners of the current node will
still receive the event
stop delivering the event. The event will not
stopPropagationImmediate Function pass on to the parent node and the rest of
the listeners of the current node

getCurrentTarget Function
get the target node that is currently
receiving the event

detail Function
custom event information(belongs to
cc.Event.EventCustom )

setUserData Function
set custom event information(belongs to
cc.Event.EventCustom )

getUserData Function
get custom event information(belongs to
cc.Event.EventCustom )

You can refer to the cc.Event and API files of its child category for a complete API list.

System built-in event


Above are the general rules for listening to the event and launching the event. Cocos
Creator has built in system events like mouse and touch for cc.Node . You can refer to
Internal Events.

235
Internal Events

System built-in events


As stated in the last file, cc.Node has a whole set of event listener and dispatch
mechanisms. Based on this mechanism, we will provide some basic system events. This file
will introduce how to use these events.

System events follow the general register method, developers can register event listener not
only by using the enumeration type but also by using the event name directly, the definition
for the event name follows DOM event standards.

// Use enumeration type to register


node.on(cc.Node.EventType.MOUSE_DOWN, function (event) {
console.log('Mouse down');
}, this);
// Use event name to register
node.on('mousedown', function (event) {
console.log('Mouse down');
}, this);

Mouse event type and event object


The Mouse event will only be triggered on desktop platforms, the event types the system
provides are as follows:

enumeration object corresponding


event trigger timing
definition event name
cc.Node.EventType.MOUSE_DOWN 'mousedown' trigger once when mouse down

when the mouse enters the


cc.Node.EventType.MOUSE_ENTER 'mouseenter' target node region, regardless if
it is down
when the mouse moves in the
cc.Node.EventType.MOUSE_MOVE 'mousemove' target node region, regardless if
it is down

when the mouse leaves the


cc.Node.EventType.MOUSE_LEAVE 'mouseleave' target node region, regardless if
it is down
trigger once when the mouse is
cc.Node.EventType.MOUSE_UP 'mouseup'
released from the down state
cc.Node.EventType.MOUSE_WHEEL 'mousewheel' when the mouse wheel rolls

236
Internal Events

The important APIs of mouse events( cc.Event.EventMouse )are as follows( cc.Event


standard events API excluded):

returned
function
value meaning
name
type

getScrollY Number
get the y axis distance wheel scrolled, effective only
when scrolling

getLocation Object
get mouse location object which includes x and y
properties
getLocationX Number get X axis location of the mouse
getLocationY Number get Y axis location of the mouse

getDelta Object
get the distance object the mouse moves since last
event, which includes x and y properties
cc.Event.EventMouse.BUTTON_LEFT or
getButton Number cc.Event.EventMouse.BUTTON_RIGHT or
cc.Event.EventMouse.BUTTON_MIDDLE

Touch event types and event objects


Touch event can be triggered in both mobile platforms and desktop platforms. This is
designed to serve developers to debug on desktop platforms better, all you need to do is
listen to touch events, touch events from mobile platforms and mouse events from desktop
can be responded to at the same time. Touch event types that the system provides are as
follows:

corresponding
enumeration object definition event trigger timing
event name
when the finger touches the
cc.Node.EventType.TOUCH_START 'touchstart'
screen

when the finger moves in the


cc.Node.EventType.TOUCH_MOVE 'touchmove'
target node region on screen
when the finger leaves screen in
cc.Node.EventType.TOUCH_END 'touchend'
the target node region

when the finger leaves screen


cc.Node.EventType.TOUCH_CANCEL 'touchcancel'
outside the target node region

The important APIs of touch event( cc.Event.EventTouch )are as follows( cc.Event


starndard event API excluded):

237
Internal Events

API name type meaning


touch cc.Touch contact object related to the current event

Note, touch events support multi-touch, each touch spot will send one event to the event
listener. You can get all the information of touch spot from cc.Touch API:

return
function name value meaning
type

getID Number
identification ID of the touch spot, can be used in
multi-touch to track the touch spot

getLocation Object
get location object of the touch spot which includes
x and y properties
getLocationX Number get X axis location of the touch spot
getLocationY Number get Y axis location of the touch spot

getDelta Object
get the distance object the touch spot moves since
the last event, which includes x and y properties

getStartLocation Object
get the location object the where touch spot gets
down which includes x and y properties

getPreviousLocation Object
get the location object of the touch spot at the last
event which includes x and y properties

Mouse and touch event bubbles


Mouse and touch events all support the event bubbles on the node tree, take the pictures
below as an example:

238
Internal Events

In the scene shown in the picture, node A has a child node B which has a child node C.
Suppose the developer set the touch event listeners for all these three nodes, when the
mouse or finger was applied in the node B region, the event will be triggered at node B first
and the node B listener will receive the event. Then the node B will pass this event to its
parent node, so the node A listener will receive this event. This is a basic event bubble
process.

When the mouse or finger presses in the node C region, the event will be triggered at node
C first and notify the registered event listener at node C. Node C will notify node B of this
event, and the logic in node B will check whether the touch spot is in its region. If the answer
is yes, it will notify its listener, otherwise, it will do nothing. Node A will receive the event
then, since node C is completely in node A, the event listener registered in node A will
receive the touch down event. The above process explains the event bubble process and
that the logic decides whether to dispatch the event or not based on the node region.

239
Internal Events

Except for the node region to decide whether to dispatch the event or not, the bubble
process of mouse and touch events is no different than the general events. So, the function
stopPropagation to call event of stopPropagation can stop the bubbling process actively.

Other events of cc.Node


enumeration object corresponding event
event trigger timing
definition name

when the location property is


null 'position-changed'
changed
when the rotation property is
null 'rotation-changed'
changed

when the scale property is


null 'scale-changed'
changed

when the size property is


null 'size-changed'
changed
when the anchor property is
null 'anchor-changed'
changed
when the color property is
null 'color-changed'
changed
when the transparency property is
null 'opacity-changed'
changed

240
Actions

Using the action system in Cocos Creator

Introduction to the action system


The action system that Cocos Creator provides originates from Cocos2d-x with both the API
and usage having been inherited. The action system can complete displacement, zoom,
rotate and all the other actions of the node within a designated time.

What needs to be noted is that the action system cannot replace the animation system.
What the action system provides is an API interface for programmers, while the animation
system is designed within the editor. Meanwhile, they serve different usages — the action
system is more suitable for making simple deformation and displacement animation while
the animation system is much more powerful, you can make animation supporting all kinds
of properties with the editor, including motion track and complicated animation in slow
motion.

Action system
The action system is easy to use, supporting the following API in cc.Node :

// create a moving action


var action = cc.moveTo(2, 100, 100);
// execute the action
node.runAction(action);
// stop one action
node.stopAction(action);
// stop all actions
node.stopActions();

Developers can also set tags for the actions and control the actions by tag.

// set tag for the action


var ACTION_TAG = 1;
action.setTag(ACTION_TAG);
// get the action by tag
node.getActionByTag(ACTION_TAG);
// stop one action by tag
node.stopActionByTag(ACTION_TAG);

241
Actions

Action categories
Cocos Creator supports various kinds of actions which can be divided into several
categories: (Since there are too many action categories, we will not describe every action's
usage in detail. The developer can check all the actions according to the action system API
list.)

Basic action
Basic action is the action to achieve all kinds of deformation and displacement animation, for
example using cc.moveTo to move the node to a certain location; using cc.rotateBy to
rotate the node by a certain angle; using cc.scaleTo to zoom in and out on the node.

Basic action can be divided into interval action and free action. Interval action is a gradual
change action that is done in a certain time interval. The actions mentioned above are all
interval actions which are inherited from cc.ActionInterval . Whereas free actions happen
immediately and are all inherited from cc.ActionInstant , for instance, cc.callFunc is used
to call the callback function; cc.hide is used to hide the node.

Container action
The container action can organize actions in different ways, below are several of the
container action’s usages:

1. Sequential action cc.sequence Sequential action makes a series of child actions run
one by one in sequence. For example:

// make the node move back and forth


var seq = cc.sequence(cc.moveBy(0.5, 200, 0), cc.moveBy(0.5, -200, 0));
node.runAction(seq);

2. Synchronization action cc.spawn Synchronization action synchronises the execution of


a series of child actions. The result of the execution of these child actions will gather
together to alter the properties of the node. For example:

// make the node zoom while it moves upwards


var spawn = cc.spawn(cc.moveBy(0.5, 0, 50), cc.scaleTo(0.5, 0.8, 1.4));
node.runAction(spawn);

3. Repetitive action cc.repeat Repetitive action is used to repeat one action several
times. For example:

242
Actions

// make the node move back and forth 5 times


var seq = cc.repeat(
cc.sequence(
cc.moveBy(2, 200, 0),
cc.moveBy(2, -200, 0)
), 5);
node.runAction(seq);

4. Repeat forever action cc.repeatForever As its name, this action container can make
the target action repeat forever until it is stopped manually.

// move the node back and forth and keep repeating


var seq = cc.repeatForever(
cc.sequence(
cc.moveBy(2, 200, 0),
cc.moveBy(2, -200, 0)
));

5. Speed action cc.speed Speed action can alter the execution rate of the target action to
make it quicker or slower.

// double the speed of the target action which means the action that took 2 secon
ds before now can be done in 1 second
var action = cc.speed(
cc.spawn(
cc.moveBy(2, 0, 50),
cc.scaleTo(2, 0.8, 1.4)
), 0.5);
node.runAction(action);

You can see from the above example, different container types can be combined. Besides,
we provide a more convenient link-form API for the container type actions. The action
objects support these three API - repeat , repeatForever , speed - which will return to the
action object itself and support the continued link-form call. Let's see a more complicated
action example:

243
Actions

// a complicated jump animation


this.jumpAction = cc.sequence(
cc.spawn(
cc.scaleTo(0.1, 0.8, 1.2),
cc.moveTo(0.1, 0, 10)
),
cc.spawn(
cc.ScaleTo.create(0.2, 1, 1),
cc.MoveTo.create(0.2, 0, 0)
),
cc.delayTime(0.5),
cc.spawn(
cc.ScaleTo.create(0.1, 1.2, 0.8),
cc.MoveTo.create(0.1, 0, -10)
),
cc.spawn(
cc.ScaleTo.create(0.2, 1, 1),
cc.MoveTo.create(0.2, 0, 0)
)
// play the animation at 1/2 speed and repeat 5 times
).speed(2).repeat(5);

Slow motion
Slow motion cannot exist alone; it always exists to modify a basic action. It can be used to
alter the time curve of the basic action to give the action fast in/out, ease in or other more
complicated special effects. One thing we need to note is that only interval actions support
slow motion:

var aciton = cc.scaleTo(0.5, 2, 2);


action.easing(cc.easeIn(3.0));

The basic slow motion category is cc.ActionEase . You can refer to the picture below for the
time curves of different slow motions:

244
Actions

Pictures from http://hosted.zeh.com.br/tweener/docs/en-us/

API reference for specific action


Please refer to the action system API list to learn which action system interfaces can be
used.

245
Action List

Action list

Basic action type


Action:base class of all action types
FiniteTimeAction:finite time action which has the property of duration .
ActionInstant:free action which will execute immediately, inherited from
FiniteTimeAction .

ActionInterval:interval action which will be completed within a predetermined time


period, also inherited from FiniteTimeAction .
ActionEase:all slow motion base classes to modify ActionInterval .
EaseRateAction:slow motion base class with rate attribute.
EaseElastic:elastic slow motion base class.
EaseBounce:bounce slow motion base class.

The developer can get to know the basic API for every action type in these action type files.

Container action
Action name Introduction File link
cc.sequence sequential execution action API description
cc.spawn synchronized execution action API description

cc.repeat repetitive execution action API description


cc.repeatForever forever repetitive action API description

cc.speed alter action rate API description

Free action

246
Action List

Action name Introduction File link

API
cc.show show immediately
description
API
cc.hide hide immediately
description
API
cc.toggleVisibility show/hide status switch
description
API
cc.removeSelf remove self from parent node
description

API
cc.flipX X-axis flip
description
API
cc.flipY Y-axis flip
description

API
cc.place place at the target location
description
API
cc.callFunc execute callback function
description
create action with existent action and a new API
cc.targetedAction
target node description

Interval action
Action name Introduction File link
API
cc.moveTo move to the target location
description

API
cc.moveBy move by assigned distance
description
API
cc.rotateTo rotate to the target angle
description

API
cc.rotateBy rotate by assigned angle
description
API
cc.scaleTo scale node to assigned multiple
description

API
cc.scaleBy scale node by assigned multiple
description

API
cc.skewTo skew to the target angle
description
API

247
Action List

description
API
cc.jumpBy move assigned distance by jumping
description

API
cc.jumpTo jump to the target location
description

API
cc.follow follow the target node's location
description
API
cc.bezierTo move to the target location by Bezier curve track
description
API
cc.bezierBy move assigned distance by Bezier curve track
description
API
cc.blink blink(based on the transparency)
description
API
cc.fadeTo alter the transparency to assigned value
description
API
cc.fadeIn fade in
description
API
cc.fadeOut fade out
description

API
cc.tintTo alter the color to the assigned value
description
API
cc.tintBy alter the color by the assigned increment
description
API
cc.delayTime delay the assigned time amount
description
API
cc.reverseTime reverse the time axis of the target action
description
move to the target location by cardinal spline API
cc.cardinalSplineTo
curve track description

move assigned distance by cardinal spline curve API


cc.cardinalSplineBy
track description

move to the target location by Catmull Rom API


cc.catmullRomTo
spline curve track description
move assigned distance by by Catmull Rom API
cc.catmullRomBy
spline curve track description

Slow motion
Action name File link

248
Action List

Action name File link

cc.easeIn API description

cc.easeOut API description

cc.easeInOut API description


cc.easeExponentialIn API description
cc.easeExponentialOut API description
cc.easeExponentialInOut API description

cc.easeSineIn API description


cc.easeSineOut API description

cc.easeSineInOut API description


cc.easeElasticIn API description
cc.easeElasticOut API description
cc.easeElasticInOut API description
cc.easeBounceIn API description
cc.easeBounceOut API description
cc.easeBounceInOut API description
cc.easeBackIn API description

cc.easeBackOut API description


cc.easeBackInOut API description
cc.easeBezierAction API description
cc.easeQuadraticActionIn API description

cc.easeQuadraticActionOut API description


cc.easeQuadraticActionInOut API description

cc.easeQuarticActionIn API description


cc.easeQuarticActionOut API description

cc.easeQuarticActionInOut API description


cc.easeQuinticActionIn API description

cc.easeQuinticActionOut API description


cc.easeQuinticActionInOut API description

cc.easeCircleActionIn API description

cc.easeCircleActionOut API description


cc.easeCircleActionInOut API description

249
Action List

cc.easeCubicActionIn API description

cc.easeCubicActionOut API description

cc.easeCubicActionInOut API description

250
Scheduler

Using the timer


In Cocos Creator, we provide a convenient timer for the components. This timer originates
from the cc.Scheduler in Cocos2d-x and we preserved it in Cocos Creator and adapted the
method of usage based on the components.

Some people may think setTimeout and setInterval are enough. Developers surely can
use these two functions, but we prefer using the timer more as it is quicker and more
powerful and it combines better with the components!

Now, let's see its detailed using method:

1. Start a timer

component.schedule(function() {
// Here ‘this’ is referring to the component
this.doSomething();
}, 5);

The timer above will run once every 5s.

2. Quicker timer

// Time interval in units of seconds


var interval = 5;
// Time of repetition
var repeat = 3;
// Start delay
var delay = 10;
component.schedule(function() {
// Here ‘this’ is referring to the component
this.doSomething();
}, interval, repeat, delay);

The timer above will start counting after 10 seconds, run call-back once every 5
seconds and repeat 3 times.

3. Timer only runs once (shortcut)

component.scheduleOnce(function() {
// Here ‘this’ is referring to the component
this.doSomething();
}, 2);

251
Scheduler

The timer above will run the call-back function once after 2 seconds and then will stop
counting.

4. Cancel the timer

The developer can use the call-back function itself to cancel the timer:

this.count = 0;
this.callback = function () {
if (this.count === 5) {
// Cancel this timer at the sixth call-back
this.unschedule(this.callback);
}
this.doSomething();
this.count++;
}
component.schedule(this.callback, 1);

Below are all the functions of the timer in the component:

schedule:start a timer
scheduleOnce:start a timer that runs only once
unschedule:cancel a timer
unscheduleAllCallbacks:cancel all the timers of this component

These detailed descriptions about API can all be found in Component API.

Besides this, if every frame needs to run a function, please add function update directly in
to the component, so this function will be called by every frame. A detailed description can
be found in life cycle file.

Caution: cc.Node does not contain API related to the


timer

252
Execution Order

Script execution order


File contents are being completed at this time...

253
Network

Standard network interface


In Cocos Creator, we support the most widely used standard network interface on the Web
platform:

XMLHttpRequest:for short connection


WebSocket:for long connection

Of course, browsers on the Web platform support these two interfaces originally. The reason
why we say Cocos Creator supports it is because when we release the native version, the
user can operate it using these two network interface codes which follows the principle of
"one set of code for multiple platforms operation" which Cocos honors.

How to use
1. XMLHttpRequest

Simple example:

var xhr = new XMLHttpRequest();


xhr.onreadystatechange = function ()
{
if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400))
{
var response = xhr.responseText;
console.log(response);
}
};
xhr.open("GET", url, true);
xhr.send();

Developers can use new XMLHttpRequest() directly or use cc.loader.getXMLHttpRequest() to


create a connecting object. The effect of these two are the same.

For the standard file of XMLHttpRequest , please refer to MDN Chinese file。

1. WebSocket

Simple example:

254
Network

ws = new WebSocket("ws://echo.websocket.org");
ws.onopen = function (event) {
console.log("Send Text WS was opened.");
};
ws.onmessage = function (event) {
console.log("response text msg: " + event.data);
};
ws.onerror = function (event) {
console.log("Send Text fired an error");
};
ws.onclose = function (event) {
console.log("WebSocket instance closed.");
};

setTimeout(function () {
if (ws.readyState === WebSocket.OPEN) {
ws.send("Hello WebSocket, I'm a text message.");
}
else {
console.log("WebSocket instance wasn't ready...");
}
}, 3);

For the standard file of WebSocket , please refer toMDN Chinese file。

SocketIO
Beyond these, SocketIO provides packaging based on the WebSocket API which can be
used on the Node.js server. If this library is needed, developers can reference SocketIO on
their own.

Reference SocketIO in script:

1. Download SocketIO:Download link


2. Drag the downloaded file into the route you would like to save in explorer
3. Reference SocketIO in the component script:

255
Network

// Judge whether it is a native environment or not, if it is then it can not be refere


nced because native provides native SocketIO to achieve
if (cc.sys.isNative) {
// io variable in native environment has not been defined, the exported variable i
s actually SocketIO
window.io = SocketIO;
}
else {
// use relative path, do not need .js as postfix
require('relative_path_to/socket.io');
}

1. To use SocketIO in the component you can go to SocketIO official website for API and
files

256
Pooling

Use object pool


Coming soon...

257
Load Assets

Acquire and load asset


Cocos Creator has a whole set of uniform asset management mechanisms. In this tutorial,
we will introduce

Classification of assets
How to set assets in the Properties panel
How to dynamically load Asset
How to dynamically load Raw Asset

Classification of assets
Assets currently can be classified into two different types, one type is called Asset, the other
is called Raw Asset.

Asset
Most assets like cc.SpriteFrame , cc.AnimationClip and cc.Prefab all belong to Asset.
The loading of Asset is uniform and automatic. Assets that rely on each other can be
preloaded automatically.

For example, when the engine is loading the scene, it will first automatically load the
assets linked to the scene and if these assets are linked to other assets, then these
other assets will also be loaded first. Only when the loading is complete will the loading
of the scene be finished.

Therefore, as long as you get an Asset object, then this object must be the one that has
finished loading and can access all the asset data directly through the attributes of this
object. If you are going to use these assets in the engine, the Asset object that the engine
API receives must be a loaded one.

The script can define an Asset properties:

258
Load Assets

// NewScript.js

cc.Class({
extends: cc.Component,
properties: {

spriteFrame: {
default: null,
type: cc.SpriteFrame
},

}
});

Raw Asset
The object received by the existing API previously in Cocos2d is not the Asset object
mentioned above but a URL presented by a character string. These former asset types that
the API uses are called Raw Assets. cc.Texture2D , cc.Font and cc.AudioClip are all
Raw Assets. If you are going to use Raw Assets in the engine, all you have to do is to pass
the URL of the asset to the engine API, then the engine interior will automatically load the
assets represented by this URL.

If you are going to declare a Raw Asset attribute type as cc.Texture2D in CCClass, you
may want to define it first:

cc.Class({
extends: cc.Component,t a
properties: {

textureURL: {
default: null,
type: cc.Texture2D
}

}
});

The problem with writing in this way is that textureURL in the code is actually a character
string rather than a living example of cc.Texture2D . To avoid confusing the two types here,
use url: cc.Texture2D rather than type: cc.Texture2D when declaring the Raw Asset
attribute in CCClass.

259
Load Assets

cc.Class({
extends: cc.Component,
properties: {

textureURL: {
default: "",
url: cc.Texture2D
}

}
});

How to set assets in the Properties panel


No matter whether using Assets or Raw Assets, as long as you define the type in the script,
you can set assets easily in the Properties panel. Hypothetically, we could have a
component like this:

// NewScript.js

cc.Class({
extends: cc.Component,
properties: {

textureURL: {
default: "",
url: cc.Texture2D
},
spriteFrame: {
default: null,
type: cc.SpriteFrame
},

}
});

Here is how it looks like in the Properties panel after adding it into the scene:

Then we drag an image and a SpriteFrame separately from Assets to the corresponding
attribute in the Properties panel:

260
Load Assets

The result is as follows:

In this way you can get the set asset directly from the script:

261
Load Assets

onLoad: function () {
var spriteFrame = this.spriteFrame;
var textureURL = this.textureURL;

spriteFrame.setTexture(textureURL);
}

Although it is very straight forward to set assets in the Properties panel, assets can only be
pre-set in the scene without dynamic switching. If you need dynamic switching, you need to
check the following contents out.

How to dynamically load


All resources that require dynamically loaded via script, must be placed under resources
folder or its subfolders, resources need to be manually created in the assets folder and
must be located in the root directory of the assets, like this:

The image/image , prefab , anim , font is a common Asset, and image, audio is a
common Raw Asset.

Inside resources folder resources, can be associated with dependence to other


resources outside the folder, or resource reference could also be an external scene to.
Project build time, but was released in build panel selected scenarios, resources all
the resources folder, resources folders associated with their dependence on external
resources are exported. So, if a resource does not need directly from the script
dynamic loading, it won't be in the resources folder.

262
Load Assets

How to dynamically load Asset


Creator provides cc.loader.loadRes the API to load specific Asset that is located under the
Resources directory. And cc.loader. load difference is that loadRe should only load a
single Asset. Invoke, you only need to pass a relative path to the resources, and Not at the
end of the path containing the file name extension.

// load Prefab
cc.loader.loadRes("test assets/prefab", function (err, prefab) {
var newNode = cc.instantiate(prefab);
cc.director.getScene().addChild(newNode);
});

// load AnimationClip
cc.loader.loadRes("test assets/anim", function (err, clip) {
myNode.getComponent(cc.Animation).addClip(clip, "anim");
});

// load SpriteAtlas (Atlas), and get one of them SpriteFrame


// Note Atlas resource file (plist) usually of the same name and a picture file (PNG)
placed in a directory,
// So should need to in the second parameter specifies the resource type.
cc.loader.loadRes("test assets/sheep", cc.SpriteAtlas, function (err, atlas) {
var frame = atlas.getSpriteFrame('sheep_down_0');
sprite.spriteFrame = frame;
});

Independent of load SpriteFrame


After the photo settings for the Sprite will be in the Resource Manager to generate a
corresponding SpriteFrame. But if test assets/image is loaded directly, and the type will be
cc.Texture2D. You must specify the second parameter is the type of resource, cc.generated
can be loaded into the picture SpriteFrame.

// load SpriteFrame
cc.loader.loadRes("test assets/image", cc.SpriteFrame, function (err, spriteFrame) {
myNode.getComponent(cc.Sprite).spriteFrame = spriteFrame;
});

If you specify a type parameter, you will find the specified resource type in the path.
When you are in the same path includes multiple names simultaneously under a
resource (for example, contains both player.clip and player.psd), or the need to obtain a
"resource" (for example, gets Texture2D SpriteFrame generated), should need to
declare types.

263
Load Assets

Resource Release
loadRes loaded in a single resource if you need to release, You can call

cc.loader.releaseRes , releaseRes incoming one with loadRes the same path parameter,

type parameters are not supported

cc.loader.releaseRes("test assets/anim");

Also, You can also use cc.loader.releaseAsset to release the instance of a specific Asset.

cc.loader.releaseAsset(spriteFrame);

How to dynamically load Raw Asset


Raw Asset can be loaded directly from a remote server using a URL, you can also
dynamically loaded from the item. In the case of remote loading, The original Cocos2d
constant loading method, using cc.loader.load can be. Raw Asset to the project, load the
same way as Asset:

// load Texture, don't add extension


cc.loader.loadRes("test assets/image", function (err, texture) {
...
});

cc.url.raw
After the success of Raw Asset loading, if you need to pass some form of URL API, you still
need to give the full path.You need to use cc.url.raw converted to a URL:

// The original URL will complain! File not found


var texture = cc.textureCache.addImage("assets/res/textures/star.png"); // Error! File
not found

// By cc.url.Raw, requiring you to declare resources directory and file name extension
var realUrl = cc.url.raw("res/textures/star.png");
var texture = cc.textureCache.addImage(realUrl); // OK!

Resource bulk loading


cc.loader.loadResAll can load multiple resources under the same path:

264
Load Assets

// loading all resource in the test assets directory


cc.loader.loadResAll("test assets", function (err, assets) {
// ...
});

// load all SpriteFrame in the sheep.plist atlas


cc.loader.loadResAll("test assets/sheep", cc.SpriteFrame, function (err, assets) {
// assets is a SpriteFrame array already contains all SpriteFrame.
// and loadRes('test assets/sheep', function (err, atlas) {...}) The entire Sprite
Atlas object is obtained.
});

265
Modular Script

Modularize script
Cocos Creator allows you to split the code into multiple script files and they can be called by
each other. To implement this, you need to know how to define and use the module in Cocos
Creator. This step is called modularize for short.

If you are not sure what modularization can do, you can consider it as:

include in C/C++

using in C#

import in Java and Python

<link> in HTML

Modularization enables you to reference other script files in Cocos Creator:

Access parameters exported from other files


Call method other files that have been exported
Use type other files that have been exported
Use or inherit other Components

JavaScript in Cocos Creator uses the Common JS standard that is almost the same as
Node.js to realize modularization, in short:

Each individual script file forms a module


Each module is an individual action scope
Reference other modules in the synchronized require method
Set module.exports as an exported variable

If you still don't quite understand, don't worry, we will explain it in here.

In this article, the two terms "module" and "script" are equivalent. All the "comment"
parts belong to advanced contents that don't need to be understood at the very start.
No matter how we define the module, all user designation codes will eventually be
compiled into native JavaScript by Cocos Creator and can be operated directly in the
browser.

Reference module
require

266
Modular Script

Other than the interface provided by Cocos Creator, all the user-defined modules will need
to call require to be accessed. For instance, we have a component defined at Rotate.js :

// Rotate.js

cc.Class({
extends: cc.Component,
// ...
});

Now if you want to access it in another script, you can:

var Rotate = require("Rotate");

What require returned is the object exported by the module. Normally, we would save the
result to a variable( var Rotate )immediately. The incoming require character string is
the module's file name, the name contains neither route nor suffix and it is case sensitive.

require complete example


Next, we can use Rotate to derive a subclass and create a new script SinRotate.js :

// SinRotate.js

var Rotate = require("Rotate");

var SinRotate = cc.Class({


extends: Rotate,
update: function (dt) {
this.rotation += this.speed * Math.sin(dt);
}
});

Here, we define a new component named SinRotate, which is inherited from Rotate, and
rewrite the update method.

This component can also be accessed by other scripts as long as you use
require("SinRotate") .

Comments:

require could be called at any place in the script at any time.

All of the script will be automatically required when the game is started. At this time, the
defined code in each module will be executed once, so no matter how many times it is
required, the same example will be returned.

267
Modular Script

When debugging, any module in the project can be required in the Console of
Developer Tools.

Define module
Define component
Each individual script file is a module, such as the new script Rotate.js mentioned above:

// Rotate.js

var Rotate = cc.Class({


extends: cc.Component,
properties: {
speed: 1
},
update: function () {
this.transform.rotation += this.speed;
}
});

When you declare a component in the script, Cocos Creator will acquiesce to export it so
other scripts can use it by requiring this module.

Define regular JavaScript module


You can not only define a component in the module, but you can also export any JavaScript
object. Let's imagine that there is a script config.js

// config.js

var config = {
moveSpeed: 10,
version: "0.15",
showTutorial: true,

load: function () {
// ...
}
};
config.load();

Now, if we want to access the config object in another script:

268
Modular Script

// player.js

var config = require("config");


cc.log("speed is", config.moveSpeed);

The result will report an error: "TypeError: Cannot read property 'moveSpeed' of null", this is
because config has not been set as the export object. We also need to set
module.exports as config at the end of config.js :

module.exports = config;

The reason for doing this is because as long as there is another script that requires it, what
they actually get will be the module.exports object in here.

So why can we define Component without setting exports ? Because Component is a


special type in Cocos Creator, if a script defines Component without declaring
exports , Cocos Creator will set exports as Component automatically.

Complete code is as follows:

// config.js

var config = {
moveSpeed: 10,
version: "0.15",
showTutorial: true,

load: function () {
// ...
}
};
config.load();

module.exports = config;

// player.js

var config = require("config");


cc.log("speed is", config.moveSpeed);

In this way, it can output correctly: "speed is 10".

More examples

269
Modular Script

Export variable
module.exports is a null object( {} )and can be added in a new field directly.

// foobar.js:

module.exports.foo = function () {
cc.log("foo");
};
module.exports.bar = function () {
cc.log("bar");
};

// test.js:

var foobar = require("foobar");


foobar.foo(); // "foo"
foobar.bar(); // "bar"

module.exports value can be any JavaScript type.

// foobar.js:

module.exports = {
FOO: function () {
this.type = "foo";
},
bar: "bar"
};

// test.js:

var foobar = require("foobar");


var foo = new foobar.FOO();
cc.log(foo.type); // "foo"
cc.log(foobar.bar); // "bar"

Packaging a private variable


Each script is a single action scope where the local variable defined using var in the script
cannot be accessed by external modules. We can package the private variable in the
module easily:

270
Modular Script

// foobar.js:

var dirty = false;


module.exports = {
setDirty: function () {
dirty = true;
},
isDirty: function () {
return dirty;
},
};

// test1.js:

var foo = require("foobar");


cc.log(typeof foo.dirty); // "undefined"
foo.setDirty();

// test2.js:

var foo = require("foobar");


cc.log(foo.isDirty()); // true

Caution: Remember to add var before the variable to be defined, otherwise it will
become the global variable!

// foobar.js:

dirty = false; // Setting dirty as the global variable is not recommended! One
Should add var before it!
module.exports = {
setDirty: function () {
dirty = true;
},
};

Circular reference
(Coming Soon...)

Third party module reference

271
Modular Script

Please refer to third party module reference file

272
Third Party Module

Third party JavaScript module reference


If you don't know anything about modular script, you should read the Modular script file first.

Currently, Cocos Creator only supports the third party npm module reference. Of course, if
what the script developer has written accords with the Node.js standard, it can also be
referenced. You can find further introduction to Node.js and npm on the official
documentation page:

Node.js modules
What is npm

How to use npm module


When you find the npm module you need, the first step you need to do is install this module
(take box2dweb-commonjs for example) in your own project directory:

> cd /path/to/project
> npm install box2dweb-commonjs

Then all you have to do is to require the module in the component script where you need
to use this module, then you are good to go:

var box2d = require('box2dweb-commonjs');

In this way, the third party module can be contained in your game automatically, even in the
packaging process it can be packaged into the game script.

Cautions
1. Only supports pure JavaScript modules:npm contains varied modules, many of
them use the API of Node.js which can not be referenced by the component because
the ultimate operating environment of the component is a browser which does not have
Node.js to support.
2. Native environments do not support DOM API:as everyone knows, browsers
contain a mass of DOM API. jQuery is one famous DOM operation library. Although
modules using these API can operate in the HTML5 environment, they cannot operate
in the native environment. This is because the native enviroment does not contain the

273
Third Party Module

web layout engine providing DOM API.

Other probable module dependence patterns in


the future
Theoretically, require can be used to reference any JavaScript script. Although it is not
currently recommended to reference third party modules in this way, it will still provide better
support in the future.

Besides, many developers are used to referencing external JavaScript script, even the off-
line script in index.html . Cocos Creator currently hasn't released how to use index.html .
Developers can only add references manually in the page file after packaging, but we are
working on how to provide a more friendly way for developers to customize index.html .

274
Web Debug Scripts

Debug script in the browser


Coming soon...

275
JavaScript Primer

JavaScript quick start


This text is adapted from A JavaScript Primer For Meteor

Overview
This text mainly introduces JavaScript. Beginners will have a general understanding about
JavaScript and would have the right skills for Cocos Creator development after they master
the contents of this text.

JavaScript is a programming language full of controversy: it is named after Java, but in fact,
it has nothing to do with Java. The creation of JavaScript only took 10 days, but it managed
to develop into the most popular Web development language in the world in 20 years. If you
are looking for the reason behind the status and popularity of JavaScript nowadays, there's
no doubt it is because of its easy-to-use language features. Of course, mastering JavaScript
is a tough task, but learning knowledge enough to develop Web Apps and games is easy. If
you have some basic programming skills, then it won't take you too long to get familiar with
JavaScript's language features.

In addition, you may use some exsiting patterns while using Cocos Creator to develop a
game under most circumstances. According to the Pareto principle (also known as the 80/20
principle), mastering 20% of one language is enough for you to handle more than 80% of
situations. Now, let's learn enough JavaScript knowledge in the shortest time so that we can
begin to develop a game with Cocos Creator.

Try when you're reading


If you can see this article, then you already have a full-featured JavaScript development
environment--I am talking about the browser you are using!

All the examples on this page, you can type them into your browser's console and check
their running results. If you don't know how to do this, you can read Guidance of how to
open the console in different browsers.

Are you ready? Let's start learning JavaScript!

Variable

276
JavaScript Primer

In JavaScript, we declare a variable like this:

var a;

Following the reserved word var is a variable name. Then we can assign the variable:

var a = 12;

When reading JavaScript code from others, you may also see variable declaration like this:

a = 12;

If you try in the browser's console, you will find JavaScript won't report an error when the
variable declaration omits var , but in the Cocos Creator project script, var of variable
declaration can not be omitted, otherwise the compiler will report an error.

Function
In JavaScript, we declare a function like this:

var myAwesomeFunction = function (myArgument) {


// does something
}

Call the function like this:

myAwesomeFunction(something);

We can see that function declaration, same as variable declaration, also follows the var
something = somethingElse pattern. Because in JavaScript, function and variable are

essentially the same, we can introduce one function as a parameter into another function
like this:

square = function (a) {


return a * a;
}
applyOperation = function (f, a) {
return f(a);
}
applyOperation (square, 10); // 100

277
JavaScript Primer

Returned value
The returned value of a function is defined by a sentence beginning with return . Here,
what we need to know is that the contents after the sentence beginning return in the
function will not be executed.

myFunction = function (a) {


return a * 3;
explodeComputer(); // will never get executed (hopefully!)
}

If
In JavaScript, a conditional judgement statement if should be used like this:

if (foo) {
return bar;
}

If/Else
If the value after if is false, the statement in else will be executed:

if (foo) {
function1();
}
else {
function2();
}

An If/Else conditional judgement can also be wrote into one line like this:

foo ? function1() : function2();

When the value of foo is true, the expression will send back the execution result of
function1() , otherwise it will send back the execution result of function2() . When we

need to assign variables according to the condition, writing it like this is very convenient:

var n = foo ? 1 : 2;

278
JavaScript Primer

The statement above can be expressed as "when foo is true, assign n as 1, otherwise
assign it as 2".

Of course, we can use else if to handle more judgement types:

if (foo) {
function1();
}
else if (bar) {
function2();
}
else {
function3();
}

JavaScript Array
In JavaScript, declare an array like this:

a = [123, 456, 789];

Access array members like this: (Start indexing from 0)

a[1]; // 456

JavaScript Object
We declare an object like this:

myProfile = {
name: "Jare Guo",
email: "blabla@gmail.com",
'zip code': 12345,
isInvited: true
}

In the grammar for object declaration( myProfile = {...} ), there is one pair of key values
separated by a comma. Each pair includes one key (character string type, sometimes
quoted by double quotation marks) and a value (could be any type: including string, number,
boolean, variable name, array, object, and even function). We call such pairs of key values a
property of the object, key is the property name and value is the property value.

279
JavaScript Primer

You can nest other objects or arrays composed by a set of objects in the value

myProfile = {
name: "Jare Guo",
email: "blabla@gmail.com",
city: "Xiamen",
points: 1234,
isInvited: true,
friends: [
{
name: "Johnny",
email: "blablabla@gmail.com"
},
{
name: "Nantas",
email: "piapiapia@gmail.com"
}
]
}

Accessing one property of the object is very easy, all we need to do is use dot grammar. It
can also combine with the array member's access:

myProfile.name; // Jare Guo


myProfile.friends[1].name; // Nantas

Objects are being largely used in JavaScript, and so is it in the function parameter passing.
For example, in Cocos Creator, we can define the FireClass object like this:

var MyComponent = cc.Class({


extends: cc.Component
});

{extends: cc.Component} is an object acting as a function parameter. In most circumstances

in JavaScript, we don't have to name an object when we use it and we may probably use it
directly like this.

Anonymous function
We have tried to use the grammar of the variable declaration to define functions:

myFunction = function (myArgument) {


// do something
}

280
JavaScript Primer

Now let's go over the method of introducing a function as a parameter into other functions:

square = function (a) {


return a * a;
}
applyOperation = function (f, a) {
return f(a);
}
applyOperation(square, 10); // 100

We have also learnt how lazy JavaScript's grammar can be, so we can use the method
below to replace multiple function declarations above:

applyOperation = function (f, a) {


return f(a);
}
applyOperation(
function(a){
return a*a;
},
10
) // 100

This time, we don't declare the square function and pass square as a parameter. Instead,
we write a new function body in the parameter spot. This is called anonymous function and
is the most extensively used pattern in JavaScript.

Chain-type grammar
Now, we will introduce a type of grammar often used in array and character string operation:

var myArray = [123, 456];


myArray.push(789) // 123, 456, 789
var myString = "abcdef";
myString.replace("a", "z"); // "zbcdef"

The point symbol in the code above means "call replace a function of the myString
character string object, and pass a and z as parameters, then get the returned value".

The biggest advantage of using point symbol expression is that you can link multiple tasks
into one expression, which of course is on the condition of each function being called having
the proper returned value. We won't spend too much time on introducing how to define a
linkable function, but it's pretty simple to use them as long as you use the following pattern:
something.function1().function2().function3()

281
JavaScript Primer

Each link in the chain will receive an original value, call a function and then pass the function
execution result to the next step:

var n = 5;
n.double().square(); //100

This
this could be the most difficult concept to understand and master in JavaScript.

In short, this key word can give you access to the object being processed; like a
chameleon, this can also change according to the execution environment.

It is very complicated to explain the principle of this , so let's use two kinds of tools to help
us understand the value of this in practice:

First of all, the most common and frequently used is console.log() . It can output the
information of an object to the browser console. Add one console.log() in the beginning of
each function body to make sure we know what object the current operating environment is
processing.

myFunction = function (a, b) {


console.log(this);
// do something
}

The other method is to assign this to another variable:

myFunction = function (a, b) {


var myObject = this;
// do something
}

At first sight, it may seem to have no effect, but it actually allows you to use the variable
myObject to imply the initial execution function object safely without being concerned about

this maybe turning into other stuff in the code after.

Operator
= is the assigning operator, a = 12 means to assign“12” to the variable a .

If you need to compare two values, you can use == , for example, a == 12 .

282
JavaScript Primer

=== is a unique operator in JavaScript, it can tell whether the value and type in both ends

are all exactly the same (type refers to string, number and so on).

a = "12";
a == 12; // true
a === 12; // false

In most cases, we recommend you to use the operator === to compare the two values,
because the situation that tries to compare two different types with the same value is very
rare.

Following is the comparison operator where JavaScript judges whether the two values are
equal or not:

a = 12;
a !== 11; // true

Operator ! can also be used alone to negate a boolean value:

a = true;
!a; // false

Operator ! will always get a boolean type value, so it can be used to transform a non-
boolean type value into a boolean type:

a = 12;
!a; // false
!!a; // true

Or:

a = 0;
!a; // true
!!a; // false

Code style
At last, the following rules on code style can help us write more specific code:

Use camel-case naming: define the variable name like myRandomVariable , but not
my_random_variable

283
JavaScript Primer

Type one ; at each end of the line, although ; in the end of a line can be ignored in
JavaScript
Put spacing before and after each keyword, such as a = b + 1 rather than a=b+1

Combine the knowledge we have learnt


The basic JavaScript grammar knowledge introduction has finished, now let's see whether
we can understand an actual Cocos Creator script code:

var Comp = cc.Class({


extends: cc.Component,

properties: {
target: {
default: null,
type: cc.Entity
}
},

onStart: function () {
this.target = cc.Entity.find('/Main Player/Bip/Head');
},

update: function () {
this.transform.worldPosition = this.target.transform.worldPosition;
}
});

This piece of code defines a new component to the engine. This component has a target
parameter, and it will be initialized into a specified object during execution and set itself to
the same coordinate as the target in every frame during the execution process.

Let's go through the function of each sentence (I will highlight useful grammar patterns):

var Comp = cc.Class({ :Here we use the object cc , call object's Class() method (this

method is one property of the cc object) by dot syntax , the parameter passing during the
call is an anonymous JavaScript object ( {} ).

target: { default: null, type: cc.Entity } :This pair of key values declare a property

named target and its value is another JavaScript anonymous object which defines the
default value and value type of the target.

extends: cc.Component :This pair of key values declare that the parent of this Class is

cc.Component. cc.Component is Cocos Creator's built-in type.

284
JavaScript Primer

onStart: function () { :This pair of key value defines a member method called onStart

whose value is an anonymous function.

this.target = cc.Entity.find(' :In the context of this sentence, this stands for the

component being created, here we access the target property by this.target .

Further study
This brief course cannot replace systematic JavaScript learning from any angle, however the
grammar patterns introduced in here can help you understand the vast majority of code in
Cocos Creator files and courses, at least from a grammar perspective.

If you prefer learning by practice like I do, then you may start to learn how to develop a
game in Cocos Creator now following the course and files!

JavaScript Resources
Here are some JavaScript primers:

JavaScript standard reference tutorial


JavaScript secret garden

285
Publish --> Web

Release a Game on Web platform


Open main menu's document/constructing release and the constructing release window.

Cocos Creator provides page templates for two kinds of Web platforms. From the pop up
menu of release platform, you can choose Web Mobile or Web Desktop . The major
difference is that in Web Mobile , the image will cover the whole browser window by default,
while in Web Desktop ,you are allowed to designate the resolution of image, which doesn't
change when you zoom on the browser window.

Release a path
You can designate a release path for the game by inputting a path in the release path input
field or choosing one via the ... browsing button. The following cross-platform release will
create resources or projects in child folders of this release path.

The default release path is in the build under the project folder . If you use version control
systems like git and svn, you can ignore the build folder in version control.

Construct and preview


The construction of Web platform is very easy. You only need to .zip scripts and resources in
the game project and resource library, and then drop them into the designated release path.
If you need test, the test mode is there for you. The sourcemap is preserved with versions
thus constructed.

Click the construct button, then a progress bar will appear on the top of the panel. When
the progress bar reaches 100%, the construction is finished.

Next, you can click the preview button to open the constructed game version in the browser
for preview and test.

286
Publish --> Web

A preview of the Web Desktop mode is shown above. You can see that the resolution of the
game image is fixed and the game image doesn't fully cover the browser window.

Release a game on Web server


If you want to release or share your games on the Internet, click the open button next to
release path. After opening the release path, copy everything in the constructed web-
mobile or web-desktop folders, and drop them into your Web server. Then you can see the

game later there.

For the construction of Web server, you can search for solutions such as Apache, Nginx, IIS
and Express on your own.

287
Cocos Framework

Install and configure Cocos Framework


Apart from the built-in game release function of Web version, Cocos Creator uses the JSB
technology based on Cocos2d-x engine for the cross-platform release of original
applications and Cocos Play smartphone web-based games. Before using Cocos Creator to
zip and send games to original platforms, you need to configure the Cocos Framework and
related development environment first.

Download and install Cocos Framework


Cocos Framework is the pre-compiled version of Cocos2d-x. Compared to the completed
version, it is small, free of compilation and easy to install. The latest version of Cocos2d-x is
v3.9. The following are download links for Cocos Framework v3.9:

Cocos Framework v3.9 for Windows


Cocos Framework v3.9 for Mac

After downloading, run the installation package, follow the instructions, and get it done.

You can choose the target path when installing Cocos Framework for Windows. The Mac
version will be installed under /Applications/Cocos/frameworks by default. Please confirm
the installation path of your Cocos Framework, because it will be configured in Cocos
Creator later.

Download SDK and NDK, which are needed for


the Android platform release
If you have no plan to release your games on Android, or you have already have a complete
Android development environment in your operating system, you can skip this section.

Download Android SDK and NDK in accordance with your operating system via the following
links:

Android SDK for Windows


Android SDK for Mac
Android NDK for Windows 32 Bit
Android NDK for Windows 64 Bit
Android NDK for Mac

288
Cocos Framework

Please unzip and drop them anywhere you like after downloading, because we need to set
up the path of Android SDK and NDK later. Don't forget where you put the unzipped versions
of the documents above.

Install C++ compiling environment


The compiling tool Cocos Console in Cocos Framework needs the following running
environment:

Python 2.7.5+, download page. Pay attention! Don't download Python 3.x version.
In Windows, the installation of Visual Studio 2013 or 2015 Community Edition is
needed, download page
In Mac, the installation of Xcode and command line tool is needed, download page

Configure path in original release


environments
Next, let's go back to Cocos Creator to configure the environmental path of the constructing
release original platform. Choose document/preference in the main menu, and open the
preference window:

We need to configure the following four paths here:

Cocos Console. It's normally in the /tools/cocos2d-console/bin directory under Cocos


Framework. The chosen path should include an executable file named cocos .
NDK, choose the NDK path that has just been downloaded and unzipped. You can skip
this if you don't need to compile on Android platform
Android SDK, choose the Android SDK path that has just been downloaded and
unzipped. You can skip this if you don't need to compile the Android platform
ANT, which will be put in the tools directory after installing Cocos Framework, which
is at the same hierarchy as frameworks . The chosen path should include an executable
file named ant .

Close the window after configuration is completed.

Notes

289
Cocos Framework

We have received lots of feedback about original packing in the public beta, and some
possible reasons are supplemented here:

1. Check the path

The path set up in preference settings should be guaranteed to be correct, for example:
the path of ant should be set under the bin directory in the ant installation directory, the
root directory of which is NDK, while the directory of Android SDK should include
documents like build-tools, platforms, etc..

2. Check NDK version

No matter which version's engine is used, you must use versions later than NDK r9b. If
Cocos2d-x framework is used, please use versions later than NDK r10, and r10e
version is recommended.

3. On Windows platform, JAVA_HOME environmental variables need to be checked

If using Windows platform, please confirm if JAVA_HOME is included in your


environmental variables. By right clicking My Computer, choosing property and opening
the advanced tab, you can check and modify environmental variables. For effective
running on Windows platform, you might need to restart the computer.

4. Check JAVA environment

Input the following code into Mac terminal or Windows command line tool for check:

java -version

If JAVA SE displays, there is no problem. If JRE displays, then you need to install JAVA
SE running environment.

5. Check if the C++ compiling environment is correctly installed in Visual Studio

When installing Visual Studio, the C++ compiling component is not ticked off by default.
If Visual Studio wasn't installed, you need to install it and choose compiling components
concerning C++.

6. Package name issue

Check the package name in the constructing release panel. Package names that
include blank space, - , etc. are all illegal.

In the end, if zipping still fails, you can try to create a standard Cocos2d-x project and
compile it. If the Cocos2d-x project is compilable and Cocos Creator couldn't be zipped,
please send the bug to us by forum.

290
Cocos Framework

291
Publish --> Native

Zip and release games on original


platforms
Open document/constructing release in the main menu and the constructing release
window.

Currently, there are five original platforms, which include: Cocos Runtime, Android, iOS, Mac
and Windows. The options of release games on Mac and Windows will only appear in
concerning operating systems.

292
Publish --> Native

Configure a Package Name


An input field named package name will appear in the constructing release window after
selecting an original platform, into which you can input the package name of your game
(also called Package Name or Bundle ID). The package name is usually arranged in the
reverse order of the product's website url, such as: com.mycompany.myproduct .

293
Publish --> Native

Only numbers, letters and underscores can be included in the package name. Besides, the
last section of package name should start with a letter, but not an underline or a number.

Construct an Original Project


After selecting the release platform and setting up the package name and initial scene, the
project can now be constructed. Click the construct button on the bottom right corner, and
start constructing workflow.

When compiling scripts and zipping resources, a progress bar will display on the top of the
window. After the progress bar has reached 100%, please continue to wait unitl the
construction of the project in console is finished. If it's successful, the diary as showed
below will display:

Built to "/myProject/tutorial-blackjack/build/tutorial-blackjack" successfully

Next, you can choose to directly open the original preview provided by Cocos Creator, or
manually open the constructed original project in IDE of corresponding platform for further
preview, adjustment and release.

294
Publish --> Native

Direct Preview
Click the preview button on the bottom right corner, you can preview games of original
platforms via the default method provided by Cocos Framework.

On Mac/iOS/Windows platforms, Cocos Simulator will be used to preview the game on the
desktop. While on Android platform, you can preview only after connecting your computer
with smartphone via USB port and opening USB test on your computer.

After clicking preview, a part of the constructing work will be continued, the real time
progress of which will be seen on the console.

Use an Original Project

Click the open button near the release path, the constructing release path will be opened in
the document manager of operating system.

jsb of this path includes all the original constructing projects.

295
Publish --> Native

The red frames in the picture indicate projects of different original platforms. Next, only by
using IDE(such as: Xcode,Eclipse,Visual Studio) that corresponds to the original platform to
open these projects, can you make further operations like compilation, preview and release.
For the usage instructions for original platform's IDE, please search related information on
your own, which will not be discussed in detail here.

296

Vous aimerez peut-être aussi