Académique Documents
Professionnel Documents
Culture Documents
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: 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).
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:
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
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.
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.
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.
12
Dashboard
When you hover your mouse over the article of a recently opened project, the available
operations on this article will appear:
Also, when you click or hover over a project, you can see the path of this project in the
status bar underneath the Dashboard.
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.
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.
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.
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.
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.
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
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!
http://fbdemos.avosapps.com/star-catcher/
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:
22
Quick Start
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.
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.
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:
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
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
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.
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).
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:
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.
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.
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.
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
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!
// 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);
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:
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
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,
40
Quick Start
// 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
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
at the bottom. Next we will use the following steps to set up this Label node:
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
// 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();
},
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!
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.
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);
},
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:
53
Cocos2d-x Guide
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:
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..
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.
56
Cocos2d-x Guide
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:
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.
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..
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.
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
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
5. node.off(type, callback, target) : Cancel the monitoring of all type events or cancel
60
Cocos2d-x Guide
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:
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
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.
// rotate by 20 degrees
this.node.rotation += 20;
Coordinate system
position , rotation and scale in cc.Node are both in the local coordinate system. As for
In Cocos Creator, if you want to calculate the world coordinate of cc.Node, you can use the
following method:
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
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
// 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 },
// define an array
// in Unity3D, it is defined as: public float[] idList;
idList: { default: [], type: cc.Float },
Life cycle
The life cycle of Cocos Creator is basically the same as Unity3D, having only slight
differences in the naming:
66
Unity Guide
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.
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.
ProjectName(project folder)
├──assets
├──library
├──local
├──settings
├──temp
└──project.json
Resource folder(assets)
‘assets’
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
QQ group:246239860
Cocos2d-JS API document
Q&A community
Code libraries needed for zipping and sending to the Android platform:
70
Support
71
Editor Overview
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.
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.
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.
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
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.
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.
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:
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
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:
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
81
Assets
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:
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.
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.
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.
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.
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.
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
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.
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
All the child nodes will be zoomed in the same ratio with the node.
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.
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
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.
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.
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
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
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:
When there are too much information in console, you can filter these information effective by
widgets in console. The operations include:
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.
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.
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 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.
102
Toolbar
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.
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 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)
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
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:
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
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.
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.
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.
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
125
Node Component
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
127
Transform
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.
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
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
136
Scene Editing
137
Sliced Sprite
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.
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.
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.
140
Multi-Resolution
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.
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
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.
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.
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.
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.
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 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.
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.
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.
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.
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.
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.
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.
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
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.
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
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
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.
158
Label Layout
In auto height adaptation mode, the 'Enable Wrap Text' property is compulsorily opened.
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.
160
UI Components
Common UI Controls
The content of this document is coming soon...
161
Auto Layout
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.
For the properties of other Layout components, please check Layout document.
164
List With Data
165
Animation
About Animation
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.
2. Press down the middle mouse button in area 2, 4, 6 in the image and drag it.
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
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.
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
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.
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
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.
172
Animation Curve
173
Sprite Animation
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.
174
Time Curve
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.
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.
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.
177
Animation Event
You can also right click Event in the animation editor and choose Delete.
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
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
When playing an animation, Animation will evaluate the former playing state of the animation
for next step operation. If animation is in:
179
Scripting Animation
anim.play('test');
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.
anim.play('test');
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
// or directly obtain
var animState = anim.getAnimationState('test');
181
Scripting Animation
From AnimationState, all the animation information can be obtained. You can use this
information to see what should be done.
The greater the speed value is, the faster the speed is, and vice versa
182
Scripting Animation
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:
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:
cc.Class({
extends: cc.Component,
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
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
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
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 ?
---`
189
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
191
Canvas
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)
192
Widget
Options
Options Explanation Note
Horizontal
HorizontalCenter center
alignment
Vertical
VerticalCenter center
alignment
193
Widget
Border alignment
We can place a Widget below Canvas, and perform the following tests:
194
Widget
Center alignment
Horizontal center alignment:
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.
196
Widget
197
Progress
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
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
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
Sprite Transition
201
Button
Button event
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
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
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
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 ?
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
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
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
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.
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
cc.Class({
extends: cc.Component,
properties: {
},
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.
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
properties: {
foo: new cc.Vec2(10,20),
bar: new cc.Color(255, 255, 255, 128),
}
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.
215
Properties
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.
216
Properties
217
Access Node Component
start: function () {
var node = this.node;
node.x = 100;
}
218
Access Node Component
start: function () {
var label = this.getComponent(cc.Label);
var text = this.name + ' started';
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".
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?");
}
}
219
Access Node Component
// 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
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);
},
// ...
});
// Cannon.js
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.
// 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.
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:
this.backNode = cc.find("Canvas/Menu/Back");
222
Access Node Component
Let's define a global object window.Global , it will cantain two properties, backNode and
backLabel .
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.
// 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,
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.
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,
225
Life Cycle Callbacks
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
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,
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,
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
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
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);
},
});
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);
},
});
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.
cc.Class({
extends: cc.Component,
properties: {
target: cc.Node,
},
start: function () {
setTimeout(function () {
this.target.destroy();
}.bind(this), 5000);
},
this.target.rotation += dt * 10.0;
},
});
231
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:
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.
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:
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:
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
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.
235
Internal 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.
236
Internal Events
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
corresponding
enumeration object definition event trigger timing
event name
when the finger touches the
cc.Node.EventType.TOUCH_START 'touchstart'
screen
237
Internal Events
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
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.
240
Actions
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 :
Developers can also set tags for the actions and control the actions by 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:
3. Repetitive action cc.repeat Repetitive action is used to repeat one action several
times. For example:
242
Actions
4. Repeat forever action cc.repeatForever As its name, this action container can make
the target action repeat forever until it is stopped manually.
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
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:
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
245
Action List
Action list
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
Free action
246
Action List
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
Slow motion
Action name File link
248
Action List
249
Action List
250
Scheduler
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!
1. Start a timer
component.schedule(function() {
// Here ‘this’ is referring to the component
this.doSomething();
}, 5);
2. Quicker timer
The timer above will start counting after 10 seconds, run call-back once every 5
seconds and repeat 3 times.
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.
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);
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.
252
Execution Order
253
Network
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:
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.
255
Network
1. To use SocketIO in the component you can go to SocketIO official website for API and
files
256
Pooling
257
Load Assets
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.
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
}
}
});
// 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
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.
The image/image , prefab , anim , font is a common Asset, and image, audio is a
common Raw Asset.
262
Load Assets
// 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 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,
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);
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:
// 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!
264
Load Assets
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#
<link> in HTML
JavaScript in Cocos Creator uses the Common JS standard that is almost the same as
Node.js to realize modularization, in short:
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,
// ...
});
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.
// SinRotate.js
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:
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
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.
// config.js
var config = {
moveSpeed: 10,
version: "0.15",
showTutorial: true,
load: function () {
// ...
}
};
config.load();
268
Modular Script
// player.js
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.
// config.js
var config = {
moveSpeed: 10,
version: "0.15",
showTutorial: true,
load: function () {
// ...
}
};
config.load();
module.exports = config;
// player.js
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:
// foobar.js:
module.exports = {
FOO: function () {
this.type = "foo";
},
bar: "bar"
};
// test.js:
270
Modular Script
// foobar.js:
// test1.js:
// test2.js:
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...)
271
Modular Script
272
Third Party Module
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
> 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:
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
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
275
JavaScript Primer
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.
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.
Variable
276
JavaScript Primer
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:
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:
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.
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:
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".
if (foo) {
function1();
}
else if (bar) {
function2();
}
else {
function3();
}
JavaScript Array
In JavaScript, declare an array like this:
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:
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:
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:
280
JavaScript Primer
Now let's go over the method of introducing a function as a parameter into other functions:
We have also learnt how lazy JavaScript's grammar can be, so we can use the method
below to replace multiple function declarations above:
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:
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.
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
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
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
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
284
JavaScript Primer
onStart: function () { :This pair of key value defines a member method called onStart
this.target = cc.Entity.find(' :In the context of this sentence, this stands for the
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:
285
Publish --> Web
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.
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.
For the construction of Web server, you can search for solutions such as Apache, Nginx, IIS
and Express on your own.
287
Cocos Framework
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 Android SDK and NDK in accordance with your operating system via the following
links:
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.
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
Notes
289
Cocos Framework
We have received lots of feedback about original packing in the public beta, and some
possible reasons are supplemented here:
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..
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.
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.
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++.
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
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
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.
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:
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.
Click the open button near the release path, the constructing release path will be opened in
the document manager of operating system.
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