Share content preview
- Mini game experience.
- Cocos Creator has lived a lifetime.
- Understanding of the basic development environment.
- Knowledge of mini game scene making.
- Basic grammar analysis.
- Sunlands-cow Demo presentation.
- Build, publish. (H5, wechat mini-game)
Mini game experience:
- Web stars: https://hytstart.github.io/game/star/
- H5 calf: https://hytstart.github.io/game/cow/
I. CoCOS Creator has existed in past life
Q: What is CoCOS Creator and what can it do?
A: CoCOS Creator is used to make games, which can be packaged and built to run on various platforms such as Web, H5, ios, Android and wechat mini games.
- Cocos Creator is a complete set of game development solutions, including the JavaScript implementation of coCOS2D-X engine, based on coCOS2D-X to achieve scripting, component-based and data-driven features.
- Past life: A brief introduction to the game engine, Cocos2D-X. It helps to learn about CoCOS Creator.
- Game engine: Any written editable computer game system or core component of an interactive real-time graphics application designed to allow game designers to create games easily and quickly without starting from scratch. In short, we, as developers, can use a variety of packaged systems (rendering engines, physics engines, collision detection systems, etc.) to facilitate development.
- Cocos2d-x: Open source game engine. You can use C++, Javascript, and Lua for game development.
- This life: The application scope of Cocos Creator mainly includes games, children’s education and so on. For example, we are familiar with happy tank war, happy mahjong.
Ii. Understanding of the basic development environment
Preparation before development: Components and entities
The workflow of Cocos Creator is centered around Component development, also known as entity-component System, which simply means that entities are built by composition rather than inheritance. Reference: Understanding the Component-entity-System (ECS \CES) game programming model
Let’s create a new coCOS Creator project and take you through the project directory files generated by creator scene editor, and finally package the compiled files.
1. Cocos Creator game development tool.
- Create a new Hello World project. Focus on resources, scenes, nodes in the scene (i.e. entities), related properties of nodes, and component libraries (components can be mounted to nodes).
- Modify string label (data driven), or the data in the script after preview. You can choose emulator or browser preview. Finally, they are mounted to the Canvas node.
The data drive here is the revolution of Creator. All scenes are serialized into pure data, which can be used at run time to reconstruct elements such as scenes, interfaces, animations, and even components.
That is, changes made in the editor are saved as JSON data, retained in version control, and acted on at run time.
2. Learn about the generated project directory file
The new Hello World project directory
-
Assets (Resources Folder)
- It is used to store all local resources, scripts and third-party library files in the game. Only contents in Assets can be displayed in Explorer.
- After each file in assets is imported into the project, a.meta file with the same name is generated. The.meta file acts as the id card for the engine to recognize the image and the related configuration set in the editor.
- Version control. Square root
-
Library
- Here the structure of the files and the format of the resources will be processed into the form needed for the final game release. That’s the resource used in the preview.
- There is no need to go into version control, it is generated every time you open the project. x
-
Settings project Settings
- Project-specific Settings, such as package name, scenario and platform selection in the Build release menu.
- Add version control. Square root
-
project.json
- Cocos Cretor identifies the project’s legitimacy flag, which defines the type of engine currently in use and where the plug-in is stored. You need project.json and assets to open your project.
- Version control. Square root
-
Bulid (Build directory)
- Package the compiled directory.
- Version control. x
3. Compiled files
- Index.html, main.js initialization correlation, including generating canvas root node correlation, etc.
- Res, document file structure, and resources.
- SRC, project.js (code dependent), setting.js (project dependent)
Three, small game scene production related knowledge. [Specific elaboration of the previous section]
In Cocos Creator, the Scene is the center of the organization of game content at development time, and the vehicle for all game content to be presented to the player. A game scene typically includes the following:
- Scene image and Text (Sprite, Label)
- role
- A script of game logic attached as a component to a scene node
When the player runs the game, the game scene will be loaded, and the game script of the contained components will be automatically run after the game scene is loaded, realizing a variety of logic functions set by the developer. So with the exception of resources, the game setting is the foundation of everything.
1. Attach a component to a scenario node.
- As described above, Cocos Creator has a component-based structure and its workflow is based on component-based development.
- A Node is an entity that carries components. By mounting components with various functions to the Node, it enables the Node to have various manifestations and functions. Multiple components can be mounted to a node, but only one render component can be added to a node, including Sprite, Label, Particle, etc.).
For example, here are the nodes (entities) in our Hello World project, node properties (the node title begins with the node properties), components, and component properties.
- Node attributes include node transformation information such as position, rotation, scale, size, anchor point, color, opacity, and other information.
- Component properties can be used to render images, render text, execute JS scripts, etc., that is, often used to render components, script components.
The relationship between nodes, node properties, and components is that the display of nodes is determined by the adjustment of node properties (zoom in, zoom out, etc.) and component rendering.
Node properties and component-related properties are described in detail.
2. Node properties
Rotation, Anchor and position are introduced.
- Rotation, counterclockwise.
- Anchor n. Determines which point in the constraint box the node uses as the position of the entire node. After we select the node, we see that the position where the transform tool appears is the anchor position of the node. Creator is the default anchor point (0.5, 0.5).
- Position, the position of a node relative to its parent node. So let’s look at the coordinate system in Creator.
Coordinate system:
- World coordinate system (absolute coordinate system) : Cocos Creator represents the unified coordinate system within the scene space in game development.
- Local coordinate system (relative coordinate system) : is the coordinate system associated with the node. Each node has its own coordinate system.
In other words, when we set the hierarchical structure of parent-child relationship in the project development setting, we modify the Position attribute of the node. At this time, the Position of the node is the local coordinate system of the node relative to the parent node rather than the world coordinate system. Finally, when drawing the entire scene, Cocos Creator maps the local coordinates of these nodes to the world coordinate system coordinates.
For example, all child nodes have their parent anchor as the origin of the coordinate system, and only care about the interior. For example, when the hero moves, the whole father will be moved. The blood bar inside will move with the mission, and the coordinates of the nodes relative to the father will remain unchanged.
3. Common components
Sprite component, Label component, Button component, code component
3.1 Sprite, the most common way to display graphics in games.
- Sprite Frame: Image resource.
- Size Mode: Specifies the Size of the Sprite. Trimmed with transparent pixels from original sources; Raw: the uncropped size of the original image is used. Custom indicates that Custom sizes are used.
- Type: Rendering mode, including Simple, Nine-walled, Tiled, Filled and Mesh rendering modes.
Key understanding: Type mode, in our use process, widely used. It makes it easier for us to manipulate images.
Sliced with nine palaces. The image will be divided into nine grids and scaled according to certain rules to fit the arbitrary size. They are often used for UI elements, or to save game space by making a grid of images that can be scaled up to infinity without compromising image quality.
For example, for rounded shapes, just stretch the middle part. (Chat bubble)
Filled mode. According to the origin, and set the fill type. You can draw the whole image in scale and direction.
Filling type: HORIZONTAL (HORIZONTAL filling), VERTICAL (VERTICAL filling) and RADIAL (fan filling) three. Horizontal padding: Display of progress bar. Fan fill: Skill CD small icon.
3.2 Label Component.
Display text, which can be a system font, TrueType font or BMFont font and art numbers. Change the font property.
3.3 the button component
- Transition: Button SpriteFrame in each state (normal, pressed, hover, disabled). Like button clicking.
- Click Events: Click Events.
Target: node with script component. Component: Name of the script Component. Handler: Specifies a callback function that is triggered when the user clicks the Button and releases it. CustomEventData: The user specifies any string to be passed in as the last argument to the event callback.
4. Script components.
Developers can add script components to nodes. In the script component, you can grab individual nodes and control them to make changes to the game. The following section elaborates on this.
Four, basic grammar analysis
Open the js file of the newly created Hello World script component.
cc.Class({
extends: cc.Component,
properties: {
label: {
default: null.type: cc.Label
},
// defaults, set visually when attaching this script to the Canvas
text: 'Hello, World! '
},
// use this for initialization
onLoad: function () {
this.label.string = this.text;
},
// called every frame
update: function (dt) {}});Copy the code
1. cc.Class
Class () is a method in the CC module that declares classes in Cocos Creator. Return a constructor. In the Creator editor, add the user script component, which is equivalent to the new constructor, which is the added instance.
2. Properties: {}, user-defined properties of the node.
You can define the location, color, size and other attributes of the node (system), as well as the type of component you write.
// 1. For example: roping a cow. Change the type of cattle and change the background.
// 2. In the thrown script component, the cowSkinType property is an array representing the type of cow.
// 3. Its type is a custom cowSkin component. The property of the cowSkin component is an array of type cc.spriteFrame, which can be used to change the background image and cause the cow to visually run.
const cowSkinComponent = cc.Class({
name: 'cowSkin'.properties: {
cowAnimate: {
type: cc.SpriteFrame,
default: [],
},
},
})
cc.Class({
extends: cc.Component,
properties: {
cowSkinType: {
type: cowSkinComponent,
default: [],}},})Copy the code
3. Life cycle
onload
When the node is activated for the first time, such as when the scene is loaded or when the node is activated. Notice that the nodes and data for the scenario are ready at this point.start
, typically used to initialize data in an intermediate state that may change during an Update. Execute after onload.update
Update the behavior, state and orientation of the object every frame (1s/frame) before rendering.onEnable
.onDisable
.lateUpdate
.onDestroy
Not commonly used.
4. This. node, the node instance to which the script component belongs.
This refers to the component instance that comes out of new. This. node, the node to which the component belongs. You can change node properties under this node, or you can find individual components and change their properties.
5. Access nodes and components.
- use
getComponent
Method to find the component on the node.
start: function () {
cc.log( this.node.getComponent(cc.Label) === this.getComponent(cc.Label) ); // true
}
Copy the code
- You can also set A property of type other component in the script, and then drag the component B that will be used into A’s property inspector. You can then retrieve the component directly from this.
- Find child nodes.
Const children = this.node.children let child = this.node.getChildByName('cow') This is suitable when the child node hierarchy is deep. Child = cc.find('Canvas/score/val', this.node)Copy the code
- Find nodes globally.
this.time = cc.find('Canvas/time/tiemLabel')
Copy the code
6. Interface properties of common nodes and components
- Access to change node properties
Start () {// activate, X = 120 this.node.y = 320 this.node.position = cc.v2(100, // // node to rotate this.node.rotation = 90 this.node.setScale(2, 2) // // change node size this.node.width = 100 this.node.height = 100 // // change color this.node.color = cc.color. RED},Copy the code
- Create, copy, and destroy nodes
const node1 = cc.instantiate(cc.Node); // Clone the node. Const node2 = cc.instantiate(cc.prefab) // Replicate Prefab node Cc.node.destroy () // destroy the NodeCopy the code
Here, prefabricated resources (prefabricated nodes). The Prefab resource CC. Prefab is suitable for general use, repeated use, and less diversity between individuals. Creating Prefab is as simple as dragging any node created in the Hierarchy Manager view to the Resource Manager view.
- Node events (system built-in, custom)
Node system events: mouse, touch,
Global system events: keyboard, gravity sensing
(1) Mouse event:
On (cc.node.eventType. MOUSE_DOWN, function (event) {console.log('Mouse down'); // Use enumeration types to register this.node.on(cc.node.eventtype. MOUSE_DOWN, function (event) {console.log('Mouse down'); }, this); // Register this.node.on('mousedown', function (event) {console.log('Mouse down'); }, this);Copy the code
Touch events, op touchstart, touchmove, touchend, touchcancel. Events give us a lot of apis to help us get location information. For example, in TouchMove, you can obtain the distance object of the contact from the last time movement according to getDelta. In a plane fight.
this.node.on('touchmove', (e) => {
const delta = e.getDelta()
const {x, y}= delta
this.node.x += x
this.node.y += y
})
Copy the code
(2) Keyboard events
onLoad () { cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, this.onKeyDown, this) }, onKeyDown(event) { const { KEY } = cc.macro switch (event.keyCode) { case KEY.a: console.log(event.keyCode) console.log(KEY.a) console.log('aaaaaaaaa') break; case 'b': console.log('bbbbbb') break; default: break; }},Copy the code
The output: At first I thought it was a simple string correspondence, but console found it was not. BBBB is not output.
(3) Custom events
Emit this.node.emit() this.node.dispatchEvent(), emit() this.node.dispatchEvent(), emit() this.node.dispatchEvent(), emit() this.node.dispatchEvent(), emit() this.node.dispatchEvent()Copy the code
- Action: Indicates the node action
(1) Declare an action type and run the action.
Const action = cc.moveto (2, 20, 300) this.node.runAction(action) // Stop an action this.node.stopAction(action); // stopAllActions this.node.stopallactions ();Copy the code
(2) Some common movements.
const a1 = cc.scaleTo(1, 30)
const a2 = cc.fadeIn(2)
Copy the code
Action list: Click Me
(3) Container action, so that each action combined movement. Cc. Sequence, cc. Spawn, cc. Repeat, cc,repeatForever.
// sequence, spawn
const ac1 = cc.moveTo(2, 50, -130)
const ac2 = cc.scaleTo(1, 4, 4)
const ac3 = cc.rotateTo(2, 90)
const sq = cc.sequence(ac1, ac2, ac3)
this.node.runAction(sq)
// repeat, repeatForever
const ac1 = cc.moveBy(2, 50, -130)
const ac2 = cc.scaleBy(1, 4, 4)
const ac3 = cc.rotateBy(2, 90)
const sq = cc.sequence(ac1, ac2, ac3)
const rep = cc.repeat(sq, 4)
this.node.runAction(rep)
Copy the code
(4) Action callback, you can handle some logic here. For example, a node in motion, to determine whether it’s touching an object.
// Action = cc.moveto (5, 20, 300) const finished1 = cc.callfunc (() => { Console. log(11111111111111111111)}) const ac2 = cc.moveto (8, 333, 4444) const end = cc.callFunc(() => { console.log(222222222222222) }) const myAction = cc.sequence(action, finished1, ac2, end); this.node.runAction(myAction)Copy the code
(5) cc.delayTime(4) delay, used with actions. For example, burst out and disappear.
(6) Slow motion.
A slow motion can never exist alone, it always exists to modify the base motion, it can be used to modify the time curve of the base motion, fast in, slow in, fast out, or other more complex effects. It is important to note that only time interval actions support easing.
Similar to cSS3’s animation-timing-function speed curve
// Node rotation, Const action = cc.rotateby (3, 360) const doAction = action.easing(cc.easeCubicActionOut()) const repAction = doAction.repeatForever(doAction) this.node.runAction(repAction)Copy the code
- Scene jump
// Scene switch cc.director. LoadScene ("test")Copy the code
7. The timer
scheduleOnce
At a timeschedule
(Callback function, interval, repetition, delay)unschedule
Cancel a timerunscheduleAllCallbacks
Cancel all timers for this component
this.scheduleOnce(() => {
console.log('scheduleOnce')
}, 2)
const interval = 4
const repeat = 3
const delay = 4
this.callBack = () => {
console.log('schedule')
this.unschedule(this.callBack)
this.unscheduleAllCallbacks()
}
this.scheduleOnce(this.callBack, interval, repeat, delay)
Copy the code
If you use schedule, you can use cc.macro.REPEAT_forever, or default to none.
8. Ajax requests
/ / XHR / / can directly use the new XMLHttpRequest () to create a connection object, but can be by cc. Loader. GetXMLHttpRequest () to create, The results are the same const url = 'https://easy-mock.com/mock/5cf0b076d205e36f67612985/test/testXhr' var XHR = new XMLHttpRequest (); xhr.onreadystatechange = function () { if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400)) { var response = xhr.responseText; console.log('response', response); }}; xhr.open("GET", url, true); xhr.send();Copy the code
5. Explanation of Sunlands-Cow Demo
Experience address: Mobile access is recommended
Before we begin, let’s go through the process:
- Build the Basic Scene
- Run of the cattle
- A rope that can be roped around a cow (movement)
- Determination of success in roping cattle.
- Settlement (bonus points, countdown), game flow control (restart, end)
- Add background music, sound prompts, particle animations
1. Set up a basic scenario
Note: (1) Modify the Canvas height of the root node, which is applicable to mobile phones. (2) Insert the relevant node, and pay attention to the attribute of button. A Button component is a button component that needs to be added to the Sprite component to control clicks. Among them, the change of touch button and the ransition attribute of button are the key points mentioned above.
2. Making of running cattle (3 types of cattle, 3 per type)
Cows need to be random, and they need to move. So we can make a prefab of a cow. Clone the preform each time it is generated.
(1) Generate three random, moving cows. Maintain a two-dimensional array to control. Mapping to our component is where we use custom components, custom types.
// The cowSkinType property is an array representing the type of cow.
// His type is a custom cowSkin component. The property of the cowSkin component is an array of type cc.spriteFrame, which can be used to change the background image and cause the cow to visually run.
const cowSkinComponent = cc.Class({
name: 'cowSkin'.properties: {
cowAnimate: {
type: cc.SpriteFrame,
default: [],
},
},
})
cc.Class({
extends: cc.Component,
properties: {
cowSkinType: {
type: cowSkinComponent,
default: [],}},})Copy the code
In the editor, each property of the COW component, the Sprite Frame corresponds to a different action of the cow.
(2) Make the cattle move by switching the background picture
OnLoad () {// Randomly generate cow this.cowType = math.floor (math.random () * 3) // And cow background change this.cowshow = this.node.getComponent(cc.Sprite) }, CowPlay (dt) {this.playtime += dt let index = math.floor (this.playtime/this.duration) // Drop the integer if (index >= This.cowaniarray.length) {index = 0 this.playtime -= (this.duration * this.cowaniarray.length)} // This.cowshow. spriteFrame = this.cowaniarray [index]},Copy the code
(3) Cattle move, in the update function, per frame * speed – offset.
This.cowspeed = -(math.random () * 300 + 200) update (dt) {const s = this.cowspeed * dt this.node.x += s}Copy the code
(4) The cow is basically finished. We want to reuse the cow component and convert it into a Prefab. Every time a new cow is generated, a cow can be generated by cloning the prefab.
- Make a prefab. Add properties to Canvas node, cowPrefab, cowPrefab. Drag the prefab into the cowPrefab property.
- At the beginning of the game, clone the preform and spawn the cow.
- After the cow is generated, a new cow is generated every other period of event after calling the function that generated the cow.
generatCow() { const newCow = cc.instantiate(this.cowPrefab) this.node.addChild(newCow) newCow.active = true Newcow.setposition (this.cowPosition.x, this.cowposition. y) // Call yourself to generate cow this.scheduleOnce(this.generatcow.bind (this), Math.random() * 3 + 2) }, startGame() { if (! This.isstart) {this.isstart = true Put all the timer to cancel this. UnscheduleAllCallbacks () enclosing generatCow ()}}, onLoad () {/ / the location of the precast body cattle enclosing cowPosition = {x: 520, y: This.isstart = false this.startGame()},Copy the code
3. A rope for a cow.
- The rope can move,
- Add the motion event to the button button.
- When the cows are set, what kind of cows are set and the background pictures of different cows should be changed. Finally set, restore the default rope.
ShootRopeOut () {if (this.isshooting) return this.isshooting = true const aniOut = cc. MoveTo (0.5, 0, shootRopeOut() {if (this.isshooting) return this.isshooting = true const aniOut = cc. -60) const aniIn = cc. MoveTo (0.5, 0, -550) const endFn = cc.callFunc(() => { this.setRopeEmpty() this.isShooting = false }, this.node) const seq = cc.sequence([aniOut, aniIn, endFn]) this.node.runAction(seq) },Copy the code
4. Determination of success of roping cattle.
- Every time
generateCow
I’m going to make cows and I’m going to save them. The cow comes out of the screen and is emptied from the array. - When the rope is thrown. Check whether the position of the cows in the array is within the preset range of the string. If so, you need to get the current cattle type and remove it from the array and node.
HitCow () {let cowType = -1 for(let I = 0; i < this.cowGet.length; I ++) {if (this.cowget [I].x >= 70 && this.cowget [I].x <= 190) {// cowType = cowType in the code component corresponding to the cow node this.cowGet[i].getComponent('cow').cowType this.cowGet[i].removeFromParent() this.cowGet.splice(i, 1) return cowType}} return -1}, // above (3). And then add the rope to the cow. Const getCow = cc.callfunc (() => {const cowType = this.gamescene.hitcow () if (cowType >= 0 && cowType <= 2) { this.node.y = 42 this.setRopeCow(cowType) } }, this.node) const seq = cc.sequence([aniOut, getCow, aniIn, endFn])Copy the code
5. Settlement (bonus points, countdown), game flow control (restart, end)
- Simply set a fixed time countdown, when the time is up, no new cows will be generated. And the corresponding settlement panel pops up.
- RePlay button, just put the beginning of the script
startGame
The event is bound to the button click event.
Note: Mask layer board, need to add a button. The influence of blocking user click behavior on lasso button. I just can’t click the lasso button anymore.
Add music and special effects
Rope to the cow, music and particle effects cue.
cc.loader.loadRes('mou', cc.AudioClip, function (err, clip) {
cc.audioEngine.play(clip);
});
Copy the code
Note: the music resources in this file need to be in the Resources directory, otherwise they will not be loaded.
7. To optimize
- The hierarchy problem with creator node: The new cow hierarchy will be above the rope, so we need to level up the rope, the rope button, and the final settlement panel.
const rope = this.node.getChildByName('rope')
rope.zIndex = 1000
const startBtn = this.node.getChildByName('startBtn')
startBtn.zIndex = 2000
this.check = cc.find('Canvas/check')
this.check.zIndex = 3000
Copy the code
- Source code can be stamped -> COCOS -creator-sunlandsCow
- .
Six, build, release. (H5, wechat mini-game)
1. Build as H5. Simply place the generated file under our static resource server and view it.
2. Build it as a wechat mini-game, which requires AppID. And, in the sequence number, set it to the game category.
View the picture in wechat development tool.
Seven,
Cocos Creator integrated processing development solution, whether direct manipulation of the screen, or combined with JS script, provides convenience. Finally, the main purpose of this sharing is to get to know Cocos Creator, how it works, and how it is used today. Interested students, can continue the next step in the animation clip system, collision detection system, micro channel game subcontracting loading and so on.
Eight, reference
- Cocos Creator V2.0 User Manual
- Understand the component-entity-System (ECS \CES) game programming model