Cocos Creator interface

Hierarchy Manager: The hierarchy manager contains all the nodes in the canvas scene

Cocos Creator common Settings

Default script editor

Cocos HelloWorld project directory structure

After a new project is created, folders such as Scene and Model will be automatically generated, as well as meta files corresponding to this folder. Cocos engine manages project resources through meta files. It stores the resource configuration information and the resource index, and the.meta file needs to be submitted to the file version control system. Asstes: all resource files of the project library: resource library, which is automatically generated after the asSTes import. When the library is damaged, you only need to delete the entire library and regenerate it. -Local: Local Settings file, which stores information about the local configuration of the project, edit panel position, window size, and location. -Local: Local Settings file, which stores information about the local configuration of the project. Project Settings, save project-related Settings, build the package name in the package menu, scene platform selection, etc

Project Settings

Main menu bar — Project — Project Settings, open the project Settings panel



The project Settings panel is mainly used in advanced Settings – project data, advanced Settings -Layers two plates

Advanced Settings – Project data: Configures the render effect of the project, such as the size of the view and the way it fits

Advanced Settings -Layers: Layers panel; In this layer, the camera can render nodes within the specified layer, and lights can illuminate parts of the scene

scenario

Cocos Creator is composed of one game scene after another. The scene is an attribute structure composed of nodes with hierarchical relationships. The scene editor is the core area for development authoring, where element nodes are edited

Nodes and components

Cocos Creator is centered on component development. Nodes are entities that carry components. We mount various components to nodes to enable them to have various functions. For example, the Button button component cannot be placed directly in the scene in the view; it must now be placed in the node.

  • Create a new empty project

  • Create a new Scene folder in asstes to store the scene files and create a new Main scene

  • Double-click the main scene to enter the main scene
  • Create a new Sprite monochrome component under the main scene root node

Incident response

Touch events

TOUCH_START: Finger touches the screen TOUCH_MOVE: finger moves on the screen TOUCH_END: finger leaves the screen when it is outside the target node area TOUCH_CANCEL: finger leaves the screen outside the target node area

Register event

Syntax: node.on(EventType, handler, scope (usually this)) this.node.on(cc.node.eventtype. TOUCH_START,callback,this) example

  • Create a new asstes/newScript.ts script and add it to the label

  • Open the component script and register the TOUCH_START event for the node in the start initialization hook.
export class NewScript extends Component {...start() {
    // Register events for the script node
    this.node.on(Node.EventType.TOUCH_START, this.handleTouch, this)}handleTouch() {
    alert("Event trigger")}... }Copy the code

Keyboard events

A keyboard event is not a node event but a system-level event. KEY_DOWN: a keyboard key is pressed. KEY_UP: a keyboard key is lifted

Register event

Syntax: systemEvent.on(event type, handler, scope (usually this)) import {systemEvent, systemEvent} from ‘cc’;

systemEvent.on(SystemEvent.EventType.KEY_DOWN, callback, this); systemEvent.off(SystemEvent.EventType.KEY_DOWN,callback, this); KEY type Macro.KEY

Custom events

Custom events are registered on the node

Register event

This.node. on(event name, event callback)

Triggered the callback

Method 1: This method fires only on the current node without bubbling this.node.emit(event name, parameter?) Const customEvent = new Event(Event name, parameter?) // Generate custom events this.node.dispatch(customEvent) // dispatch custom events to the time stream

Game resources

A game is often composed of a large number of resources, so managing multimedia resources including images, audio, fonts, particles, maps and so on is also a core function of a game engine. The management of resources probably includes the organization, running, loading and cleaning of resources as well as the operation and optimization of resources

Image Resource Management

The game’s image resources are also called maps, and Cocos not only supports PNG/JPG, import of atlas resources, and automatic generation of atlas resources

A single image

1. Create a new source folder in asstes to save image resources. 2, In resource Management, Ctrl+ S save the scene, generate asstes/scene/main. Scene structure is as follows:



3. Double-click Main to enter the Main scene. Delete the built-in camera and lights and change the viewport to 2D mode.

4. Set the image type tosprite-frameSave and drag the image to the scene.

Mount the image to the Sprite node1. Create a scene firstspriteObject and place the image (which must be of type Sprite-frame) into thespriteThe node’sspriteFrameOn the properties

Atlas of resources

An Atlas, also known as a Sprite Sheet, is a common art resource. He uses specialized tools to combine multiple images into one large image and indexes resources through format files such as PList. The atlas resources available to CocosCreator consist of PList and PNG. Plist stores the location, size and other information of each sub-image in the atlas. To use the atlas resource, you need to put the PNG and PLIST files of the atlas together into the resource manager.

Sound Resource Management

Games are not just about simple interfaces and animations, but also music and sound effects. Good sound in a scene can greatly improve the user experience.

WebAudio

In CC(Coocs Creator), audio is loaded in the same way that images are added in the explorer path. The property inspector of the node can choose how to load the audio. CC provides WebAudio(the default) and DomAudio. Load audio resources through WebAudio, in the engine is in the form of a buffer cache, the characteristics of this way is: good compatibility, less problems, but occupy more memory resources. Example 1. Right-click the scene node in the Hierarchy Manager to create an empty node and mount the Audio component under the empty node

2. Drag the audio resource from Explorer to the Clip property of the Audio component. After rendering the project, the audio is successfully loaded into the project (after the project is rendered, the audio will play after clicking)

DomAudio

The sound resource is played by generating a standard Audio element, which is cached. Some browsers may encounter compatibility issues when using the standard audio element to play sound resources. For example, iOS browsers do not support volume adjustment, and all volume properties will not be valid. Cocos load audio mode defaults to WebAudio, and when WebAudio mode is not supported on the Web, the engine automatically rolls back to DomAudio mode. DomAudio has many limitations and must be triggered by some action event per playback (WebAudio only needs to trigger once) to enforce DomAudio use:

assetManager.loadRemote('http://example.com/background.mp3', {
    audioLoadMode: AudioClip.AudioType.DOM_AUDIO,
}, callback);
Copy the code

The precast body

The concept originally came from Unity as a reusable game object. For example: bullets, soldiers, enemies, bricks in the wall

Create using preforms

Create a monochrome Sprite node in the scene and add new functionality to the node (collision system, scripting, etc.). Then drag the nodes configured in the hierarchy selector to The explorer to form a prefab (.prefab file) so that we can use the prefab in the Explorer under any node

The text

CC has system text, can also render text word. CC supports system text, dynamic font, and bitmap text

System text

Using CC system text, create the Label node and then modify the properties panel

String: label Indicates the text content of a node

UseSystemFont: Specifies whether to use the system text. This parameter is selected by default

The dynamic text

CC currently supports dynamic text in TFF format. Drag the TFF file to Explorer to complete the import of dynamic text

Bitmap words

Dynamic text is not suitable for Chinese, bitmap text can solve the problem of using Chinese fonts in CC.

Bitmap text production

Bitmap text consists of an FNT text file and a PNG image. The FNT file provides an index of each character minimap, which is generated by a dedicated bitmap font maker. The common ones are hiero and BMFONT

Import and use of bitmap fonts

1. Drag the.fnt and.png bitmap fonts into Explorer. 2. Drag the. FNT file to the font property of the Label node.

Particle system

It can be very expensive to do gorgeous effects with normal animation (it takes up a lot of memory), and particle systems are a good solution. It fires a lot of tiny, random particles and renders them more efficiently than a single Sprite. It can simulate random smoke, lightning, wind, rain, and snow falling effects.

CC particle resources

CC’s Particle system can be created through Particle Designer or online via the webwww.effecthub.com/particle2dx .

Using particle

Particle files are also. Plist files, which record particle emission coordinates, rules and other information. Drag the particle file into explorer, create a new particle node, and drag the particle file onto the file property of the particle node.

You can also edit the particle system if you check the Custom option

Atlas resource management

Game maps are often duplicated, and the duplicated parts are called elements.

Tiled map editor

Tiled characteristics

1. Map data files can be used in a variety of encoding forms, which can be used in different game engines. 2. Operation of paste, undo and so on 5, have the concept of pixel, hierarchy, object and so on 6, automatically load pixel set and so on 7, tiLED resources at least two kinds:

  • . TMX map data
  • .png atlas texture
  • .TSX tileset data profile (part of.TMX file required)

Download and Install

Download it at www.mapeditor.org/

The use of the tiled

Open the prepared material and enter the TiLED operation interface



Note:

Cocos Creator 3.0 supports TiledMap V1.2.0, but I have tile map resources lower than 1.2. So the Cocos Creator used here is version 2.4.5.

Use map resources in CC

Create a new project using Cocos Creator 2.4.5

To make it easier for CC to parse tiLED resources (tiles), create a map folder in Explorer. Then drag the tile map resource into the map.



The first:

Drag and drop the.TMX file of the Tiled resource directly into the scene

The second:

In the scenario, create an empty node. Add the TiledMap component to the empty node and drag the. TMX file of the Tiled resource to the tmxAsstes property of the TiledMap component.

Skeletal animation

Traditional animation is to achieve the animation of objects through key frames. And bone animation can achieve control object object vertex, to achieve animation. It is practiced through resources exported by Spine

Skeletal Animation Resources

.json/.skel: skeleton data, save the data of the character skeleton, different parts of the size position range of motion. PNG: atlas texture, save the different body parts of the character. TXT /.atlas: atlas texture and atlas data constitute a complete character skin

Import skeletal animation resources

Since the version of my bone animation resource is low, I still need to create the CC project of version 2.4.5 and create the spine folder in Resource Manager to save all the bone animation files



The first:

Drag and drop the skeletal animation JSON file directly into the scene

Second: Create an empty node in the scene and add the Spine Skeleton component to it. Drag and drop the skeleton animation JSON file to the Skeleton Data property of the Spine Skeletion component.



Click animation in the Properties panel to select the animation to render

The Bone animation component property inspector values properties

Animation: Animation: Animation to render Loop: whether to Loop Premuliplied Alpha: whether to use premultiply map TimeScale: The default value is: 1 Debug Slots: indicates whether to display Slot debugging information. Debug Bone: indicates whether to display Bone debugging information. After this parameter is selected, node data of Bone resources can be displayed in the scenario editor

Bone animation component important method

ClearTrack () : clears the animation sp.Skeleton instance of all playing queues. ClearTrack (0) : Cleaning index 0 playback queue animation sp. Skeleton instance. SetAnimation (animationName index, isLoop) : Setting a broadcast animation of queue queue all the animation to play will cover before sp. The Skeleton instance. AddAnimation (animationName index, isLoop) : like the play, the animation is added to the queue in front of the animation will not cover. The entire animation queue executes in sequence

  • Index: indicates the index of the playback queue. The type is Number
  • AnimationName: String name of the bone animation
  • IsLoop: indicates whether to play in a loop. The type is Boolean
Sp. Skeleton instance. SetAnimation (0."start".false)
Copy the code

Bone animation events

Sp.skeleton instance setStartListener(callBack,this): triggered when the animation starts setEndtListener(callBack,this): triggered when the animation ends SetCompleteListener (callBack,this): This is triggered when the animation is played once, or multiple times when the animation is played in a loop

The sample

In this example, we need to display the bone animation in the scene, and we can add a new bone animation with a button.



1, newSpine_scene scenarioAnd create a new one in the sceneBlank nodes has beenAnd three control display animationsThe Button node



2,Spine nodeaddSkeleton componentsAnd bind theBone animation. Json file.Skeleton componentsNo animation is checked by default



3, newSpine_canvas. Js scriptAnd mountThe root node CanvasOn.

  // spine_canvas.js
  // Declare the spineSke property to interface bind sp.Skeleton
  properties: {
    spineSke: {
      default: null.type: sp.Skeleton
    }
  },
  onLoad() {
    // Get the spine node
    const spine = this.node.getChildByName("spine")
    // Get the spine_skeleton component
    const ske_com = spine.getComponent(sp.Skeleton)
    this.ske_com = ske_com
    this.ske_com.setAnimation(0."walk".true)},// Click the button to set the animation queue
   setAnimate(type, customData) {
    // Clear the playback queue
    this.ske_com.clearTrack(0)
    // Set the playback queue
    this.ske_com.setAnimation(0, customData, false)
    // Add an animation to the playback queue
    this.ske_com.addAnimation(0."walk".true)}Copy the code

4. Open the script property check of the root Canvas and add the spineSke property of the spine node



5. Set the name of the animation to be displayed for the three button click events with the outgoing parameters death, hit, and jump

scripting

The script of CC is mainly developed by expanding components and created by using scripts to create a new script folder under ASSTES to save all script files, create a new index script under script, add script components for the scene node and register the index script.



Add a print statement to the script start hook

start() { cc.log("hello world") }A printed message appears on the renderer console

Class declarations

Classes in CC are implemented as examples through cc.class

// Declare a class named Sprite
let Sprite = cc.Class({ 
  / / the name of the class
  name: "sprite".// Instance method
  print() {
    cc.log("The instance's print method is called.")}})start() {
  / / instantiate
  const sprite = new Sprite() 
  cc.log(sprite instanceof Sprite)
  sprite.print()
}  
Copy the code

Declare custom properties

Custom attributes refer to properties, which are used to set parameters for the game. After adding custom attributes to the script, the corresponding options will be added to the properties panel

A simple statement

Simple declarations of properties are in the form of key-value pairs, and the values of properties are divided into primitive types and array types

  • Basic types of
properties:{
    height:20.//number
    type:"actor".//string
    loaded:false.//boolean
    target:null      //object
}

Copy the code



When declared properties have types, you can pass in their constructors at the declaration

properties:{
  target:cc.Node,
  pos:cc.Vec2,
  age:cc.Number
}
Copy the code

  • An array type

When declaring an array of attributes, you can fill in their type or constructor at the declaration

properties:{
  any: [].bools:[cc.Boolean],   // Do not define an array of a specific type
  Strings:[cc.String],
  floats:[cc.Float],
  frame:[cc.SpriteFrame]
}
Copy the code

Complex statement

A complex declaration refers to a complex declaration of an object whose attribute value is a key-value pair. Type: indicates the type of the property, for example, cc.Number or cc.node displayName: indicates the name of the property displayed tooltip: indicates the message displayed when you hover over the property name. Visible: If visible is set to false, serializable will not be serialized (saved) when it is set to false. If visible is set to False, serializable will not be serialized

  properties: {
    score: {
      default: 20.type: cc.Number,
      displayName: "Score".tooltip: "This is a hint tool."}}Copy the code

  • An array type

The default value of the array type must be [], and the type must be declared if the property is to be edited in the properties pane

  properties: {
    name: {default: [].type:[cc.String]
    },
    enemies: {default: [].type:[cc.Node]
    }
  }
Copy the code

Script lifecycle functions

OnLoad: This is triggered when the component is initialized for the first time to acquire other nodes. OnEnable: Triggered when component Enable changes from False to true or active changes from False to true. Execution order: onLoad–onEnable–start onUpdata: Triggered when the game is updated, usually within the completion of some key frame (the state size of the object) operation

onUpdata(dt) {
// donUpdata will take an argument dt, which is the current frame distance from the last frame. If the device is 60 frames then DT is equal to 1/60
}
Copy the code

LateUpadate: This is triggered before all animations are executed, if we need to do something after some dynamic effect (particle, etc.) updates, or if we need to do something else after all component updates have been executed: OnDestry is triggered when a component’s enable property changes from True to false, or when active changes from true to false. This callback is triggered when a component or node calls destry()

Access nodes/components

We can modify nodes through the CC panel, but there are scenarios where we need to dynamically modify nodes/components based on user input and current logic

Obtain the node where the component resides

Access the this.node variable in the component’s methods

start() {
  // Get node Modify node axis position
  const node = this.node  
  node.x = 100
}
Copy the code

Gets other components under the current node

start() {
    const label = this.getComponent(cc.Label)  
    let text = this.name + 'started'
    label.string = text
}
Copy the code

Get other nodes

Declare a custom property in the current node script, bind other scripts to this custom property, and use this custom property to get the bound node in the script


  properties: {
    depNode: {
      default: null.type: cc.Node
    }
  },
 start() {
   cc.log("Get the dependent node".this.depNode)
 }
Copy the code

In CCIDE, you create two monochrome nodes in a scene and bind one of them to the other.

Gets components under other nodes

In the scenario, there are two nodes named nodeA and nodeB. How do I get the script components for nodeB from nodeA? 1. Create scene Main and rename two monochrome Sprite nodes to nodeA and nodeB



2. Create scriptA script and mount it to the Script component of NodeA node. Create scriptB script and mount it to nodeB node.

// scriptB  
// Declare a method in scriptB.
hello() {
  cc.log("ScriptB script hello method called")}Copy the code

Declare custom property scriptB in scriptA script to bind scriptB script components

// scriptA
// Introduce the component type
const scriptB = require("scriptB")
 properties: {
   scriptB: {default:null.// Declare the type of the bound attribute
     type:scriptB
   }
 }
 start() {
   / / get scriptB
   const scriptB = this.scriptB
   // Call the scriptB method
   scriptB.hello()
 }
Copy the code

Get child nodes

Children get single child node: node.getChildByName(” child name “) Get deep child node: cc.find(” child name/grandchild name “,this.node) get global arbitrary node: Cc.find (“Canvas/ node name/node name..” Example 1. Create main. Create a parent node in main without binding the parent script



2. Create many new child nodes under the parent node and get all the child nodes in the parent script

start () {
  // Get a collection of child nodes
  const childList = this.node.children
  childList.forEach(element= > {
      // Get the node name
      console.log("Node Name",element.name);
  });
  const nodeA = this.node.getChildByName("nodeA")
  const grandChildA = cc.find("nodeA/grandChildA".this.node)
},
Copy the code

Node Activation Status

Active = fasle/true To obtain the node activation state: Node. ActiveInHierarchy note: The update hook of a node is triggered every frame when the node is active. The onEnable hook of a node is triggered when the node is inactive. The onDisable hook of a node is triggered when the node is active and closed

Change the parent node of a node

Node. removeFromParent = parent node.parent = parent node.removeFromParent = parent node.removeFromParent Whether to clear events and actions bound to the node,flag is true by default.node.removeFromParent (flag) // Insert the current node into the parent node addChild = (node)

start() {
  // Get the parent node
  const canvasNode = cc.find("Canvas")
  // Change the parent node in the first way
  this.node.parent = canvasNode  
  // Change the parent node in the second way
  this.node.parent.removeFromParent(false)  
  canvasNode.addChild(this.node)
}
Copy the code

The child node of an index node

Get all the children of a node array: Node. children Number of children: node.childrenCount Note that these two apis can only get direct children, not children of children

Change the node transformation (position, rotation, scale, size)

Modify the coordinates

1. Direct modification

node.x = 50  
node.y = 100  
Copy the code

SetPosition (X, Y)

node.setPosition(50.100)  
node.setPosition(cc.v2(50.100))
Copy the code

3, through node.position

node.postion = cc.v2(50.100)
Copy the code

Cc. v2 API for creating 2d space vector coordinate objects Note: The modified position is relative to the parent node

Node rotation

node.setRotation(90) or node. Rotation =90  
Copy the code

Node scale

node.scaleX = 2  
node.scaleY = 2Or node. SetScale (2)  // Scale width and height at the same time
node.setScale(2.2)  
Copy the code

Modifying the Node Size

node.setContentSize(100)  
node.setContentSize(100.100)  
node.setContentSize(cc.size(100.100)) or node. Width =100
node.height = 100
Copy the code

The anchor nodes

The node anchor is located in the center of the node by default. The default values are 50 and 50

node.anchorX = 1  
node.anchorY = 0Or node. SetAnchorPoint (1.0)
Copy the code

Node color and opacity

To change the color and transparency of basic rendering components such as Sprite and Label, you can only do this on the node example, because the CC itself does not set up apis for these basic rendering components

// Set the node color
node.color=cc.Color.RED  
// Set the node opacity
node.opacity = 128   / / range of 0-255
Copy the code

Common Interfaces of Components

This. Enabled: Whether the component update method is executed every frame to control the display of the component. Update (DT): component member method. OnLoad: a component member method that is triggered when the component’s owning node is initialized start: executed before the component’s first update, usually after all components have executed onLoad

Create a node

Dynamically loading resources: cc.loader.loadres (resource name, resource type, callback after loading) new Node: new cc.node (Node name) addComponent to Node: node.addcomponent (cc.sprite) note: To dynamically load resources, you must create the Sources folder under Assets and place all resources in the Sources folder. Example 1. Create a resources folder under Assets and add avatar. PNG image and create index.js. Create a new empty node in the scenario and add the script component binding index.js

start () {
// Save the current script instance
  const self = this
// Dynamically load assets/resources, load Avatar resources and declare the resource type, complete the loading callback, parameter 1 is an error message, Cc.loader. loadRes("avatar", cc.spriteFrame,function(err, SpriteFrame){
  // Generate a Sprite node
  let node = new cc.Node("sprite")
  // Add a Sprite component to the Sprite node
  let sp = node.addComponent(cc.Sprite)
  // Set the spriteFrame property of the Sprite node
  sp.spriteFrame = spriteFrame  
  // Insert the Sprite node into the current script component node
  node.parent = self.node  
  // Set this to the Sprite node size
  node.setContentSize(100.100)})}Copy the code

Clone node

Existing node in clone scenario: cc.instantiate(this.target) example

cc.Class({
  extends:cc.Component,
  properties: {target: {default:null.type:cc.Node
    }
  },
  start() {
    const node = cc.instantiate(this.target)  
    node.parent = this.node
    node.setContentSize(50.50)
    node.setPosition(0.0)}})Copy the code

Create a prefabricated node

Creating a prefab node is similar by simply setting the prefab node type example

cc.Class({
  extends:cc.Component,
  properties: {target: {default:null.type:cc.Prefab
    }
  },
  start() {
    const node = cc.instantiate(this.target)  
    node.parent = this.node  
    node.setContentSize(50.50)
    node.setPosition(0.0)}})Copy the code

Destruction of the node

Note: When a node is destroyed, it is not immediately removed. Instead, it is executed uniformly after the current frame logic is updated. When a node is destroyed, it will be in an invalid state. You can use cc.isValid to determine an example of the state

start () {
  setTimeout(() = >{
    this.node.destroy()
  },2000)
},
update (dt) {
  if(cc.isValid(this)) {
    cc.log("Component valid")}},Copy the code

RemoveFromParent: When a node calls removeFromParent, it does not have to be completely released from memory and may cause a memory leak destroy: This object is completely destroyed and onDestroy is triggered

Loading Switching Scenarios

In CC scripts, the scene can be loaded through the loadScene method of the director class. Cc.director. LoadScene (Scene name, callback after scene loading (optional))

preload

Some scenarios take too long to load, causing delays. You can use preloading. The scene is cached in memory ahead of time. Cc.director. PreloadScene (“main”,function() {cc.log(‘ scene loading completed ‘)})

Resident nodes are used to manage scenario resources and transfer parameters

The engine can only run one scenario at a time. When switching scenarios, all nodes and other instances in the scenario are destroyed by default. If we need a component to control the loading of all scenarios, or scenarios pass parameters directly. Requires the components in the node editor for permanent node, make him when switching scenarios will not be automatically remove cc. Game. AddPersistRootNode resident (node) is marked nodes, mount the components on the node load continuous function in the scene. Remove cc resident node. Game. RemovePersistRootNode (node)

Resource management

In CC, all types that inherit from CC.asstes are collectively called resources. For example, cc.Text2D, cc.SpriteFrame, cc.AnimationClip, cc.Prefab, etc.

How do I set resources in resource Picker

1. Create a monochrome Sprite node as the background and bind the index script



2. Declare a custom property sprite_frame in index to bind the resource rendering source

sprite_frame:{
  default:null.type:cc.SpriteFrame
}
Copy the code

3. In CC, bind the resource to the scipte sprite_frame property of the background node



4. In Index, get the Sprite component and set its render source as the background image of the background node

onLoad () {
  // Get the Sprite component of the node
  const sprite = this.node.getComponent(cc.Sprite)
  // Change the render source for Sprite components
  sprite.spriteFrame = this.sprite_frame
}
Copy the code

Dynamically loading resources

LoadRes: cc.loader.loadRes(resource path, resource type, callback after loading)

const self = this  
cc.loader.loadRes("Pler".(err,prefab) = >{
  // Clone a prefabricated node
  const newNode = cc.instantiate(prefab)
  // Insert the prefabricated node into the current node
  self.node.addChild(newNode)
})
Copy the code

Resource Release

Cc.loader. ReleaseRes (Resource path, resource type (optional)) Release specific Assets instance cc.loader. ReleaseAsset (spriteFrame)

Action system

CC provides the Action system, which can realize the displacement, scaling, rotation and other actions of the node within a certain period of time. The Action class of CC is not the object displayed on the screen, and the Action must rely on the node class and its subclass instances.

The basic use

// Create an action
// cc. MoveTo (cycle, X coordinates, y coordinates)
const action = cc.moveTo(2.100.100)  
// Perform the action
this.node.runAction(action)  
// Stop an action
this.node.stopAction(action)  
// Stop all actions
this.node.stopAllActions()
Copy the code

Action type

Basic action

Cc. moveTo: moves a node to a certain position cc.moveBy: moves a node based on its current position cc.rotateBy: moves a node to a certain Angle cc.scaleTo: Basic actions of zooming node are divided into interval action and instant action. Interval action: Complete gradient action within a certain interval. All these actions inherit from cc.ActionInterval Instant action: It happens immediately, such as cc.callfunc for calling functions, cc.hide for hiding nodes, all inherited from cc.ActionInstant

Container movement

Container actions can combine different actions. Sequential action: To perform a series of actions one by one in sequence

// Move the node left and right
let seq = cc.sequence(cc.moveBy(0.5.200.0),cc.moveBy(0.5, -200.0))
node.runAction(seq)
Copy the code

Synchronized actions: All actions are executed synchronously

// Make the node scale as it moves
let action = cc.spawn(cc.moveBy(0.5.200.0),cc.scaleTo(0.5.0.8.1.4))  
node.runAction(action)
Copy the code

Repetition: To repeat an action several times

// Move the node back and forth 5 times
let action = cc.repeat(
cc.sequence(cc.moveBy(0.5.200.0),cc.moveBy(0.5, -200.0)),5
)
node.runAction(action)
Copy the code

Permanent repeat: To make an action repeat indefinitely until manual stop

// Move the node back and forth 5 times
let action = cc.repeatForever(
cc.sequence(cc.moveBy(0.5.200.0),cc.moveBy(0.5, -200.0)))
node.runAction(action)
Copy the code

Speed action: Change the execution rate of the target action to make it complete faster or slower

// Make the target action twice as fast as it takes 4 seconds to complete in 2 seconds
let action = cc.speed(
cc.sequence(cc.moveBy(0.5.200.0),cc.moveBy(0.5, -200.0))),2
node.runAction(action)
Copy the code

Action is the callback

Action callbacks can trigger a callback cc.callfunc after an action has completed.

// Declare an action callback
let finished = cc.callFunc(
  function(target,score){
    cc.log("Action callback")},this.100
)
// Register the action callback for the action
// Register the action callback for only one of the actions
    let action = cc.sequence(cc.moveBy(1,cc.v2(0.100)),cc.fadeOut(1),finished)
// Register the action callback for each action
    let action = cc.sequence(cc.moveBy(1,cc.v2(0.100)), finished, cc. FadeOut (1),finished)
Copy the code

The UI system

In addition to gameplay, the biggest workload of a game is the development of the UI interface. CC has been greatly improved in ease of use after several iterations.

Base render component – Sprite component

Sprite components are the most common images for 2D rendering images.

Render images using Sprite components

1. Create a blank node and add Sprite components to the blank node. Drag the image into the spriteFrame property of the Sprite component. 2. Create a New Sprite node in the scene and drag the image onto the spriteFrame property of the Sprite component.

Sprite properties

Atlas: SpriteFrame: Used to save single image resources. Type: rendering mode, Simple, tender, Tiled, Filled SizeMode Trimmed with resource sizes, Trimmed after node size (with resource original size, Trimmed automatically), Raw(with resource original size, not Trimmed after resource size), Custom(Custom resource size) Trim: If checked, the transparent pixel area around the original image will be removed during rendering. This parameter only takes effect when Type is set to Simple. SrcBlendFactor: current image blending mode (default Settings are generally used) Background image Blending mode (generally use the default Settings) render mode

  • Plain mode (Simple): Render the Sprite as the original resource looks
  • Nine-grid mode: The image is divided into nine-grid and zoomed in accordance with certain rules
  • Tiled mode: The image does not stretch when Sprite increases in size. Instead, repeat the original image size over the entire Sprite
  • Filled mode:

    Draws a portion of the original image in a certain direction and scale according to the origin and fill mode Settings. Often used for dynamic display of progress bars.

    After the fill mode is selected, a new set of properties can be configured
    • FillType: type of filling, HORIZONTAL(HORIZONTAL filling), VERTICAL(VERTICAL filling), RADIAL(fan filling)
    • FillStart: indicates the start point of filling (0-1). In horizontal mode, the filling starts from the left
    • FillRange: FillRange (0-1), set to 1, will fill up to the full range of the original image
    • FillCenter: indicates the filling center. This parameter is available only when the filling type is sector. It determines which point around the Sprite to fan fill. Anchor point function similar to coordinate system
  • Mesh mode: To use this mode, plist files must be packed with TexturePacker 4.x and ploygon algorithm

Base render component -Lable component

The Lable component is used to display a text, which can be system text. You can also use pictures or art words.

Lable Common attributes

String: text content String HorizontalAlign: text horizontal alignment, LEFT, CENTER, RIGHT VerticalAlign: text vertical alignment, TOP, CENTER, BOTTOM FontSize: Current support CLAMP, SHRINK, RESIZE_HEIGHT EnableWrapText: Whether to enable text wrapping (in typesetting mode set to CLAMP and SHRINK effective) SpacingX: spacing between texts. Font: specifies the Font file required for text rendering. If the Font is system text, the value can be empty FontFamily: specifies the Font name for text. CacheMode: specifies the Font name for text rendering. The text cache type is used to optimize applications and is only valid for system text or TTF fonts

  • NONE: The default value. The entire text in Label will generate a bitmap
  • BITMAP: The selection will also generate a BITMAP of the text, but will try to participate in dynamic composition. This pattern is mainly used for infrequently updated labels because dynamic composite graphs take up more memory. Note: If a scenario has a large number of labels with the same text, it is recommended to reuse the memory space in CHAR mode
  • CHAR: This principle is a bit self-explanatory

UseSystemFont: Boolean value, whether to use system text

Button Button component

Button components can respond to user clicks. When the user clicks Button, the Button itself will have state changes. Button allows users to respond to a custom action after clicking.

The Button properties

Target: type of Node when Transition occurs on a Button. Interactable: Boolean. When set to false, the Button component is disabled. Transition: enum types including NONE, COLOR, SPRITE, and Scale. For details about the different Transition Settings for each type, see the Button Transition section ClickEvent: List type, which is empty by default. Each event added by the user consists of a node reference, a component name, and a corresponding function. The Transition of a Button is used to specify the state of a Button when the user clicks on it. At present, there are four main types: NONE, COLOR, SPRITE and SCALE

  • COLOR: Button COLOR that can be configured as normal, click, hover, or disabled
  • SPRITE: Button image resources that can be configured in normal, click, hover, and disabled states
  • SCALE: Allows you to set the time and SCALE factor for the component to SCALE when clicked

Button click event

Add the callback Target via the property inspector: node with script Component: script Component name Handler: callback function triggered when the user clicks CustomEventData: User specifies any string passed in as the last argument to the event callback

// btn.js declares the onClick method
onClick() {
  cc.log("The BTN component has been clicked")}Copy the code

Note: This method is convenient, but has limitations. It cannot get the screen coordinates of the button when the user clicks on it. Create a btnHandle script and bind it to any node or component

 properties: {
   // Declare the custom button property to bind the button component
   button: cc.Button
 },
 onLoad() {
   // Register the click event for the button component
   this.button.node.on("click".this.onClick, this)},onClick() {
    cc.log("Click on the Button component")}Copy the code

Animation system

In addition to the standard shift, rotate, scale, and sequence frame animations, the CC animation system also supports the drive of arbitrary component properties and user-defined properties, as well as editable time curve and movement path editing. Can let the use of this does not write a line of code to make a variety of fine animation CC animation editor for less complex need to link with logic, such as UI animation. If you need complex special effects, character animations, or nested animations, consider Spine or DragonBones.

Animation

Animation component

CC can configure the states of different frame nodes to achieve Animation through the Animation component

Clip animation

Clip is a resource file type, save the Animation statement data in advance (node movement track, node change cycle, key frames, etc.), to mount it to the Animation component, to apply the Animation data on a node example 1, the main scene, new new monochromatic Sprite node (bg) as a white background, Create a monochrome Sprite node (box) as the moving object

2. Add the box nodeAnimation componentClick Create Clip Assets/ RES/Move (Clip) and click in the upper left corner to edit the Assets



3. In the animation editor, the upper left side is the node information, the lower side is the node property list, and the right side is the animation timeline. The red line on the timeline represents key frames.



4. Create property Postion and set keyframes for the property



5. Drag the key frame to set the key frame position of the node in the next state. Then drag the node in the scene editor to set the node position



Save the animation clip and mount the animation clip to the Box nodeAnimationdefault clipProperties, render the item

Animation editor interface

Basic operations of the animation editor

Change the scale of the timeline by rolling the mouse wheel in the 2/4/6 area of the figure to scale and shrink the scale of the timeline display. Move the display area. If you want to view the edited key frame on the right side, you can right click and drag to view the shortcut key: left: move a frame forward. CTRL/CMD + left: Go to frame 0 CTRL/CMD + Right: go to the last valid frame

The data inside the clip

Node data

Animation clips through the node location of the data is defined, the rest of the child node with the root node index of relative path to find the corresponding data, sometimes after completion of the animation will rename nodes Can cause animation data loss problem Solve the problem of data path loss Click the missing data – click mobile data, to modify the data path