### Include Default Game Launch Logic and Custom Script Source: https://docs.cocos.com/creator/4.0/manual/en/editor/preview/browser.html This example shows how to modify the index.ejs file to include the default game launch logic and then load a custom script after the game has started. ```html ...
... <%- include(cocosTemplate, {}) %> // Game launch processing logic // Add a new script ``` -------------------------------- ### Install Gulp and Project Modules Source: https://docs.cocos.com/creator/4.0/manual/en/advanced-topics/engine-customization.html Installs gulp globally and then installs project-specific modules. Ensure Node.js and npm are installed. ```bash npm install -g gulp npm install ``` -------------------------------- ### Install http-server Package Source: https://docs.cocos.com/creator/4.0/manual/en/editor/publish/publish-fb-instant-games.html Install the http-server package globally using npm. This is a prerequisite for setting up a local web server. ```bash cd fb-instant-games npm install -g http-server ``` -------------------------------- ### Install Dependencies and Build Extension Source: https://docs.cocos.com/creator/4.0/manual/en/editor/extension/create-extension.html Execute these commands in your extension's directory to install necessary Node.js modules and compile the extension for use. ```bash npm install npm run build ``` -------------------------------- ### Install vivo-minigame/cli Globally Source: https://docs.cocos.com/creator/4.0/manual/en/editor/publish/publish-vivo-mini-game.html Installs the vivo-minigame command-line interface globally. Ensure your Node.js version is compatible; upgrade if installation fails. ```bash npm install -g @vivo-minigame/cli ``` -------------------------------- ### Extension Directory Structure Example Source: https://docs.cocos.com/creator/4.0/manual/en/editor/extension/store/upload-store.html This is an example of the expected directory structure for an extension package. Ensure your extension follows this format before zipping. ```text foobar |--panel |--index.js |--package.json |--main.js ``` -------------------------------- ### Install APK via ADB Source: https://docs.cocos.com/creator/4.0/manual/en/editor/publish/google-play-games/build-and-run.html Install the built APK file to the emulator using the adb install command. ```bash adb install C:/yourpath/yourgame.apk ``` -------------------------------- ### cc_plugin.json File Example Source: https://docs.cocos.com/creator/4.0/manual/en/advanced-topics/native-plugins/brief.html A concrete example of a `cc_plugin.json` file, showing typical values for name, version, author, engine version, and modules. ```json { "name":"hello-cocos-demo", "version":"1.0.0", "author":"cocos", "engine-version":"> =3.6.3", "disabled":false, "modules":[ { "target":"hello_cocos_glue" } ], "platforms":["windows", "android", "mac", "ios", "google-play"] } ``` -------------------------------- ### Custom Mac Platform Implementation (C++) Source: https://docs.cocos.com/creator/4.0/manual/en/engine/template/native-upgrade-to-v3.5.html Example of creating a custom platform class for Mac, inheriting from MacPlatform and overriding initialization and run methods. This allows for custom application setup and message loop handling. ```cpp #include "platform/BasePlatform.h" #include "MyAppDelegate.h" class CustomMacPlatform : public MacPlatform { public: // Rewrite the initialization method of the platform int32_t init() override { // Calling the methods of the parent class return MacPlatform::init(); } // Here you enter the message loop of oc until the program exits int32_t run(int argc, const char** argv) { id delegate = [[MyAppDelegate alloc] init]; NSApplication.sharedApplication.delegate = delegate; return NSApplicationMain(argc, argv); } } ``` -------------------------------- ### Initialize and Use Geometry Renderer Source: https://docs.cocos.com/creator/4.0/manual/en/geometry-renderer/index.html This example demonstrates how to initialize the geometry renderer in the start function and add a circle to it every frame in the update function. Ensure the Geometry Renderer is enabled in Project Settings and your project is 3D based. ```typescript import { _decorator, Component, Camera, Color } from 'cc'; const { ccclass, property, executeInEditMode} = _decorator; @ccclass('Geometry') @executeInEditMode(true) export class Geometry extends Component { @property(Camera) mainCamera:Camera = null; start() { this.mainCamera?.camera.initGeometryRenderer(); } update(deltaTime: number) { this.mainCamera?.camera?.geometryRenderer?.addCircle(this.node.worldPosition, 1, Color.GREEN, 20); } } ``` -------------------------------- ### Example Custom Build Hook Functions Source: https://docs.cocos.com/creator/4.0/manual/en/editor/publish/custom-build-plugin.html Provides simple examples of implementing `onBeforeBuild` and `onBeforeCompressSettings` hook functions. These functions can be asynchronous. ```typescript export function onBeforeBuild(options) { // Todo some thing... } export async function onBeforeCompressSettings(options, result) { // Todo some thing... } ``` -------------------------------- ### Basic CMake Project Setup Source: https://docs.cocos.com/creator/4.0/manual/en/advanced-topics/cmake-learning.html Sets the minimum CMake version, defines the project name and language, and adds an executable target. This is a foundational setup for most C++ CMake projects. ```cmake cmake_minimum_required(VERSION 3.10) # Set project name and main language project(helloworld CXX) add_executable(helloworld main.cpp) ``` -------------------------------- ### Check Git Installation Source: https://docs.cocos.com/creator/4.0/manual/en/submit-pr/submit-pr.html Verify if Git is installed on your system by running the 'git' command in the terminal. If Git is installed, it will display its version and usage information. ```bash git ``` -------------------------------- ### Start Local HTTPS Server Source: https://docs.cocos.com/creator/4.0/manual/en/editor/publish/publish-fb-instant-games.html Start the http-server locally with SSL enabled, listening on port 8080 and bound to 127.0.0.1. The -c-1 flag disables caching. ```bash http-server --ssl -c-1 -p 8080 -a 127.0.0.1 ``` -------------------------------- ### Setting Up the Rendering Process Per Camera Source: https://docs.cocos.com/creator/4.0/manual/en/render-pipeline/write-render-pipeline.html This snippet shows how to set up the rendering process for each camera within the pipeline during the `setup` method, which is called once per frame. It iterates through sorted cameras, emits pipeline events, and builds a simple pipeline for each. ```typescript class BuiltinPipelineBuilder implements rendering.PipelineBuilder { setup( cameras: renderer.scene.Camera[], ppl: rendering.BasicPipeline, ): void { for (const camera of cameras) { if (!camera.scene || !camera.window) { continue; } this._pipelineEvent.emit(PipelineEventType.RENDER_CAMERA_BEGIN, camera); this._buildSimplePipeline(camera, ppl); this._pipelineEvent.emit(PipelineEventType.RENDER_CAMERA_END, camera); } } } ``` -------------------------------- ### Get Component on the Same Node Source: https://docs.cocos.com/creator/4.0/manual/en/scripting/access-node-component.html Retrieve a component of a specific type from the same node using `getComponent`. This example retrieves a `LabelComponent`. ```typescript import { _decorator, Component, LabelComponent } from 'cc'; const { ccclass, property } = _decorator; @ccclass("test") export class test extends Component { private label: any = null start(){ this.label = this.getComponent(LabelComponent); let text = this.name + 'started'; // Change the text in Label Component this.label.string = text; } } ``` -------------------------------- ### Golang HTTP Server Example Source: https://docs.cocos.com/creator/4.0/manual/en/advanced-topics/http.html Sets up a basic HTTP server using Golang that listens on port 8080 and responds with 'http request received'. This is useful for testing client-side HTTP requests. ```go package main import ( "fmt" "log" "net/http" ) func handler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "http request received") } func main() { http.HandleFunc("/", handler) log.Fatal(http.ListenAndServe(":8080", nil)) } ``` -------------------------------- ### Enable UIStaticBatch via Script Source: https://docs.cocos.com/creator/4.0/manual/en/ui-system/components/editor/ui-static.html Use this TypeScript code to get the UIStaticBatch component and start static batching. Call `markAsDirty()` to initiate the collection of rendering data. ```typescript import { _decorator, Component } from 'cc'; const { ccclass, property } = _decorator; @ccclass("example") export class example extends Component { start(){ const uiStatic = this.node.getComponent(UIStaticBatch); // Choose the time you want to start static batching, call this interface to start static batching uiStatic.markAsDirty(); } } ``` -------------------------------- ### Migrating Application Initialization in `game.ejs` Source: https://docs.cocos.com/creator/4.0/manual/en/release-notes/build-template-settings-upgrade-guide-v3.6.html Demonstrates the updated pattern for initializing and starting the application using System.import and the Application class, as required in `game.ejs` or `index.ejs`. ```javascript System.import('<%= applicationJs %>') .then(({ Application }) => { return new Application(); }).then((application) => { return System.import('cc').then((cc) => { return application.init(cc); }).then(() => { return application.start(); }); }).catch((err) => { console.error(err.toString() + ', stack: ' + err.stack); }); ``` -------------------------------- ### Listen for Mouse Click Events Source: https://docs.cocos.com/creator/4.0/manual/en/getting-started/first-game-2d/index.html Register a listener for mouse up events in the `start` method to trigger callbacks. This setup is essential for handling user input like clicks. ```typescript start () { input.on(Input.EventType.MOUSE_UP, this.onMouseUp, this); } ``` -------------------------------- ### Drawing a Closed Path with close() Source: https://docs.cocos.com/creator/4.0/manual/en/ui-system/components/editor/graphics/close.html Use the close() method after defining path segments to connect the last point back to the starting point. This example draws a shape and then strokes it. ```typescript const ctx = node.getComponent(Graphics); ctx.moveTo(20,20); ctx.lineTo(20,100); ctx.lineTo(70,100); ctx.close(); ctx.stroke(); ``` -------------------------------- ### Get Current Animation Transition Status Source: https://docs.cocos.com/creator/4.0/manual/en/animation/marionette/animation-controller.html Obtain information about the current transition of the animation state machine at a specified layer (layer 0 in this example). This includes transition duration and time. ```typescript let transition: animation.TransitionStatus = animationController.getCurrentTransition(0) console.log(transition.duration, transition.time) ``` -------------------------------- ### Build Web Desktop with Debug Mode (Windows) Source: https://docs.cocos.com/creator/4.0/manual/en/editor/publish/publish-in-command-line.html Example of building a web desktop project with debug mode enabled on Windows using the command line. Ensure the correct CocosCreator executable path and project path are specified. ```bash ...\CocosCreator.exe --project projectPath --build "platform=web-desktop;debug=true" ``` -------------------------------- ### Get Current Animation State Status Source: https://docs.cocos.com/creator/4.0/manual/en/animation/marionette/animation-controller.html Retrieve the normalized progress of the current animation state at a specific layer (layer 0 in this example). Requires an active Animation Controller component. ```typescript let states: animation.MotionStateStatus = animationController.getCurrentStateStatus(0) console.log(states.progress) ``` -------------------------------- ### BuiltinPipelineBuilder: Setup Method Source: https://docs.cocos.com/creator/4.0/manual/en/render-pipeline/write-render-pipeline.html Sets up the render pipeline for multiple cameras, dynamically choosing between a full or simple pipeline based on camera configurations. ```typescript setup(cameras: renderer.scene.Camera[], ppl: rendering.BasicPipeline): void { for (const camera of cameras) { if (!camera.scene || !camera.window) { continue; } // get camera information setupCameraConfigs(camera, this._configs, this._cameraConfigs); this._pipelineEvent.emit(PipelineEventType.RENDER_CAMERA_BEGIN, camera); // build render pipeline according to the camera information. if (this._cameraConfigs.useFullPipeline) { this._buildForwardPipeline(ppl, camera, camera.scene); } else { this._buildSimplePipeline(ppl, camera); } this._pipelineEvent.emit(PipelineEventType.RENDER_CAMERA_END, camera); } } } ``` -------------------------------- ### Component Scripts with onLoad, start, and update Source: https://docs.cocos.com/creator/4.0/manual/en/scripting/component.html Example TypeScript code for two components, CompA and CompB, demonstrating their lifecycle methods. The execution order depends on their arrangement in the Inspector panel. ```typescript // CompA.ts import { _decorator, Component, Node } from 'cc'; const { ccclass, property } = _decorator; @ccclass("CompA") export class CompA extends Component { onLoad () { console.log('CompA onLoad!'); } start () { console.log('CompA start!'); } update (deltaTime: number) { console.log('CompA update!'); } } ``` ```typescript // CompB.ts import { _decorator, Component, Node } from 'cc'; const { ccclass, property } = _decorator; @ccclass("CompB") export class CompB extends Component { onLoad () { console.log('CompB onLoad!'); } start () { console.log('CompB start!'); } update (deltaTime: number) { console.log('CompB update!'); } } ``` -------------------------------- ### Implementing Custom Logic via Engine Startup Events Source: https://docs.cocos.com/creator/4.0/manual/en/release-notes/build-template-settings-upgrade-guide-v3.6.html This snippet demonstrates the new method for implementing custom logic by listening to engine startup events like onPreBaseInitDelegate, onPostBaseInitDelegate, and onPostProjectInitDelegate within the new application.ejs template. ```javascript init (engine) { cc = engine; cc.game.onPreBaseInitDelegate.add(this.onPreBaseInit.bind(this)); // Listening for engine start process events onPreBaseInitDelegate cc.game.onPostBaseInitDelegate.add(this.onPostBaseInit.bind(this)); // Listening for engine start process events onPostBaseInitDelegate cc.game.onPostProjectInitDelegate.add(this.onPostProjectInit.bind(this)); // Listening for engine start process events onPostProjectInitDelegate } onPreBaseInit () { customLogic1(); // Customized Logic 1 } onPostBaseInit () { customLogic2() // Customized Logic 2 } onPostProjectInit () { customLogic3() // Customized Logic 3 } ``` -------------------------------- ### Display Plugin Directory Contents After Setup Source: https://docs.cocos.com/creator/4.0/manual/en/advanced-topics/native-plugins/tutorial.html Verify the plugin directory structure after creating the source and CMake files, showing the `src` directory alongside `include` and `windows`. ```console $ tree native/native-plugin/ native/native-plugin/ ├── include │ └── hello_cocos.h ├── src │ ├── CMakeLists.txt │ └── hello_cocos_glue.cpp └── windows ├── hello_cocos_glue-config.cmake └── lib ├── hello_cocos.lib └── hello_cocosd.lib ``` -------------------------------- ### Drawing a Cubic Bezier Curve with bezierCurveTo Source: https://docs.cocos.com/creator/4.0/manual/en/ui-system/components/editor/graphics/bezierCurveTo.html This example demonstrates how to use the bezierCurveTo method to draw a cubic Bezier curve. It requires a Graphics component and sets the starting point before defining the curve's control points and end point. ```typescript const ctx = node.getComponent(Graphics); ctx.moveTo(20,20); ctx.bezierCurveTo(20,100,200,100,200,20); ctx.stroke(); ``` -------------------------------- ### GameManager Component Setup Source: https://docs.cocos.com/creator/4.0/manual/en/getting-started/first-game/index.html Set up the main GameManager component in TypeScript for Cocos Creator. This includes importing necessary modules, defining block types, declaring properties for prefabs and road length, and initializing the road array. The `start` method is used to call the road generation logic. ```typescript import { _decorator, Component, Prefab } from 'cc'; const { ccclass, property } = _decorator; // Track grid type, pit (BT_NONE) or solid road (BT_STONE) enum BlockType { BT_NONE, BT_STONE, }; @ccclass("GameManager") export class GameManager extends Component { // The runway prefab @property({type: Prefab}) public cubePrfb: Prefab | null = null; // Total road length @property public roadLength = 50; private _road: BlockType[] = []; start () { this.generateRoad(); } generateRoad() { } } ``` -------------------------------- ### Unity Shader Syntax Example Source: https://docs.cocos.com/creator/4.0/manual/en/guide/unity Illustrates the syntax for defining a custom shader in Unity using the ShaderLab language. ```shader Shader "Transparent/Cutout/DiffuseDoubleside" { Properties { _Color ("Main Color", Color) = (1,1,1,1) _MainTex ("Base (RGB) Trans (A)", 2D) = "white" {} _Cutoff ("Alpha cutoff", Range(0,1)) = 0.5 } SubShader { Tags {"IgnoreProjector"="True" "RenderType"="TransparentCutout"} LOD 200 Cull Off CGPROGRAM #pragma surface surf Lambert alphatest:_Cutoff sampler2D _MainTex; float4 _Color; struct Input { float2 uv_MainTex; }; void surf (Input IN, inout SurfaceOutput o) { half4 c = tex2D(_MainTex, IN.uv_MainTex) * _Color; o.Albedo = c.rgb; o.Alpha = c.a; } ENDCG } Fallback "Transparent/Cutout/VertexLit" } ``` -------------------------------- ### Execute Bundle Build via Command Line (Windows) Source: https://docs.cocos.com/creator/4.0/manual/en/editor/publish/publish-in-command-line.html Command to execute a bundle build on Windows. Specify the project path, stage as 'bundle', and the configuration path. ```bash ...\CocosCreator.exe --project projectPath --build "stage=bundle;configPath=./bundle-build-config.json;" ``` -------------------------------- ### Installing Python Dependencies for Auto-Binding Source: https://docs.cocos.com/creator/4.0/manual/en/advanced-topics/jsb-auto-binding.html Installs necessary Python dependencies, `pyyaml` and `Cheetah3`, required for the JSB auto-binding script. Ensure you have Python 3.0 installed. ```shell sudo pip3 install pyyaml==5.4.1 sudo pip3 install Cheetah3 ``` -------------------------------- ### Install Project Dependencies Source: https://docs.cocos.com/creator/4.0/manual/en/scripting/modules/config.html Reinstall all project dependencies listed in `package.json`. This is useful for setting up the project on a new machine or after pulling changes. ```bash > npm install ``` -------------------------------- ### Check npm Installation Source: https://docs.cocos.com/creator/4.0/manual/en/scripting/modules/config.html Verify that npm is installed correctly by checking its version. This command should be run in your terminal. ```bash > npm -v # Possible output. # 6.14.9 ``` -------------------------------- ### YAML Reference Example Source: https://docs.cocos.com/creator/4.0/manual/en/shader/yaml-101.html Shows how to use YAML anchors (&) to define reusable data blocks and references (*) to include them elsewhere. ```yaml object1: &o1 key1: value1 object2: key2: value2 key3: *o1 ``` ```json { "object1": { "key1": "value1" }, "object2": { "key2": "value2", "key3": { "key1": "value1" } } } ``` -------------------------------- ### Verify Emscripten Installation Source: https://docs.cocos.com/creator/4.0/manual/en/advanced-topics/wasm-asm-create.html Run this command to confirm that Emscripten has been successfully installed and is accessible from your command line. ```bash emcc --version ``` -------------------------------- ### Install CMake on macOS Source: https://docs.cocos.com/creator/4.0/manual/en/advanced-topics/cmake-learning.html Use Homebrew to install CMake on a macOS system if you need to use it from the command line. ```bash brew install cmake ``` -------------------------------- ### Initialize Player Controller and Input Handling Source: https://docs.cocos.com/creator/4.0/manual/en/getting-started/first-game/index.html Set up the PlayerController component, including initializing input event listeners for mouse clicks. ```typescript import { _decorator, Component, input, Input, EventMouse, Vec3 } from 'cc'; const { ccclass, property } = _decorator; @ccclass("PlayerController") export class PlayerController extends Component { // Whether to receive the jump command private _startJump: boolean = false; // The jump step private _jumpStep: number = 0; // Current position of the character private _curPos: Vec3 = new Vec3(); // The target position of the character private _targetPos: Vec3 = new Vec3(); start () { // Your initialization goes here. input.on(Input.EventType.MOUSE_UP, this.onMouseUp, this); } onMouseUp(event: EventMouse) { } update(dt: number): void { if( this._startJump){ } } } ``` -------------------------------- ### Create a Simple C Code File Source: https://docs.cocos.com/creator/4.0/manual/en/advanced-topics/wasm-asm-create.html This is a basic C program that prints 'Hello World' to the console. It serves as a starting point for Wasm compilation. ```c #include