### Example package.json Configuration Source: https://github.com/layabox/layaair-doc-zh/blob/LayaAir3.3/_book/basics/IDE/importJsLibrary/readme.html This is an example of a package.json file after installing the 'astar-typescript' package. It lists the project's name, version, description, main entry point, scripts, author, license, and dependencies. ```json { "name": "test", "version": "1.0.0", "description": "", "main": "index.js", "bin": { "test": "bin/bundle.js" }, "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "dependencies": { "astar-typescript": "^1.2.5" } } ``` -------------------------------- ### Start Server with Node.js Source: https://github.com/layabox/layaair-doc-zh/blob/LayaAir3.3/_book/libs/Protobuf/readme.html Execute this command in the terminal to start the server-side code for Protobuf communication. ```bash node server.js ``` -------------------------------- ### Example Usage Source: https://github.com/layabox/layaair-doc-zh/blob/LayaAir3.3/_book/basics/common/device/geolocation/readme.md Example demonstrating how to use `Geolocation.watchPosition` and `Geolocation.clearWatch` in a LayaAir script. ```APIDOC ```typescript const { regClass, property } = Laya; @regClass() export class NewScript extends Laya.Script { constructor() { super(); } onKeyDown(): void { // Geolocation.watchPosition function signature Laya.Geolocation.watchPosition( Laya.Handler.create(this, this.updatePosition), Laya.Handler.create(this, this.onError)); console.log("keydown"); } updatePosition(info: Laya.GeolocationInfo): void { console.log('经纬度: (' + info.longitude + '°, ' + info.latitude + '°),精确度:' + info.accuracy + 'm'); } onError(err: any): void { var errType: String; if (err.code == Laya.Geolocation.PERMISSION_DENIED) errType = "Permission Denied"; else if (err.code == Laya.Geolocation.POSITION_UNAVAILABLE) errType = "Position Unavailable"; else if (err.code == Laya.Geolocation.TIMEOUT) errType = "Time Out"; console.log('ERROR(' + errType + '): ' + err.message); } } ``` ``` -------------------------------- ### Message Handling Example Source: https://github.com/layabox/layaair-doc-zh/blob/LayaAir3.3/_book/released/native/platform_communication/readme.html An example demonstrating how to set up message callbacks and send results back to JavaScript. ```APIDOC ## Message Handling Example ### Description This C++ code snippet shows how to implement message handling by setting callbacks for synchronous and asynchronous messages and then sending results back to JavaScript using `conchSendHandleMessageResult`. ### Code ```c++ int main(int argc, char *argv[]) { conchSetHandleMessageCallback( [](const char *eventName, const char *data) -> void { if (strcmp(eventName, "syncMessage") == 0) { conchSendHandleMessageResult(eventName, "sync message from platform"); } }, [](const char *eventName, const char *data) -> void { if (strcmp(eventName, "asyncMessage") == 0) { conchSendHandleMessageResult(eventName, "async message from platform"); } }); return conchMain(argc, argv); } ``` ``` -------------------------------- ### GET Request Example Source: https://github.com/layabox/layaair-doc-zh/blob/LayaAir3.3/_book/basics/common/network/HTTP/readme.html Example of sending a GET request using LayaAir's HttpRequest. GET requests are suitable for retrieving resources and passing data via the URL. ```APIDOC ## GET Request Example ### Description This example demonstrates how to send an HTTP GET request using the `HttpRequest` class in LayaAir. GET requests are typically used to fetch data from a server and append parameters to the URL. ### Code ```typescript // Create an HttpRequest object const xhr = new Laya.HttpRequest(); // Send an HTTP GET request. Data is appended to the URL, suitable for cases where no large data needs to be sent. xhr.send('https://httpbin.org/get', null, 'get', 'text'); ``` ``` -------------------------------- ### Build and Serve GitBook Locally Source: https://github.com/layabox/layaair-doc-zh/blob/LayaAir3.3/README.md This command first builds the documentation and then starts a local web server. It defaults to listening on port 4000, allowing you to preview the documentation in your browser. ```bash gitbook serve ``` -------------------------------- ### Example Usage of watchPosition Source: https://github.com/layabox/layaair-doc-zh/blob/LayaAir3.3/_book/basics/common/device/geolocation/readme.html Example demonstrating how to use `Geolocation.watchPosition` to get real-time location updates and handle potential errors. ```APIDOC ## Example Usage of watchPosition ### Description This example shows how to initiate location monitoring and handle the received position information or any errors that occur. ### Code ```typescript const { regClass, property } = Laya; @regClass() export class NewScript extends Laya.Script { constructor() { super(); } onKeyDown(): void { // Geolocation.watchPosition function signature Laya.Geolocation.watchPosition( Laya.Handler.create(this, this.updatePosition), Laya.Handler.create(this, this.onError)); console.log("keydown"); } updatePosition(info: Laya.GeolocationInfo): void { console.log('经纬度: (' + info.longitude + '°, ' + info.latitude + '°),精确度:' + info.accuracy + 'm'); } onError(err: any): void { var errType: String; if (err.code == Laya.Geolocation.PERMISSION_DENIED) errType = "Permission Denied"; else if (err.code == Laya.Geolocation.POSITION_UNAVAILABLE) errType = "Position Unavailable"; else if (err.code == Laya.Geolocation.TIMEOUT) errType = "Time Out"; console.log('ERROR(' + errType + '): ' + err.message); } } ``` ``` -------------------------------- ### Open UI Prefab Example Source: https://github.com/layabox/layaair-doc-zh/blob/LayaAir3.3/_book/basics/common/Scene/readme.md Shows how to open a UI implemented as a prefab. ```typescript Laya.Scene.open("dailog.lh"); ``` -------------------------------- ### Install a Node.js Version with NVM Source: https://github.com/layabox/layaair-doc-zh/blob/LayaAir3.3/README.md Use this command to install a specific version of Node.js, for example, 10.24.1. This is recommended for managing multiple Node.js versions. ```bash nvm install 10.24.1 ``` -------------------------------- ### Example: Get Item with Create Function Source: https://github.com/layabox/layaair-doc-zh/blob/LayaAir3.3/_book/basics/common/Pool/readme.md Demonstrates using `getItemByCreateFun` to get a 'Bullet' object. If the pool is empty, a new 'Bullet' is created, optionally added back to the pool, and then returned. ```typescript let bullet = Laya.Pool.getItemByCreateFun("Bullet", function() { // 创建一个子弹 let bullet = new Bullet(); // 拿到子弹的对象池 var pool = Laya.Pool.getPoolBySign("Bullet"); // 把子弹放入对象池,也可以不放入对象池,根据开发者需求 pool.push( bullet ); // 返回子弹对象 return bullet; }); ``` -------------------------------- ### Initialize Project with npm init Source: https://github.com/layabox/layaair-doc-zh/blob/LayaAir3.3/_book/basics/IDE/importJsLibrary/readme.html Run 'npm init' in your project folder to generate a package.json file. This file records project details and dependencies. Configuration options can be accepted by pressing Enter. ```bash npm init ``` -------------------------------- ### Install and Import npm Package (AStar Example) Source: https://github.com/layabox/layaair-doc-zh/blob/LayaAir3.3/_book/basics/IDE/importJsLibrary/readme.md Use npm to install third-party packages like 'astar-typescript' and import them into your LayaAir scripts using the 'import' statement. This method is recommended for managing project dependencies. ```json { "name": "test", "version": "1.0.0", "description": "", "main": "index.js", "bin": { "test": "bin/bundle.js" }, "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "dependencies": { "astar-typescript": "^1.2.5" } } ``` ```typescript import { AStarFinder } from "astar-typescript"; const { regClass, property } = Laya; @regClass() export class Main extends Laya.Script { private aStarInstance: AStarFinder; onStart() { console.log("Game start"); // 0表示通路,1表示障碍 let myMatrix = [ [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 1, 1, 0, 1, 1, 0], [0, 0, 1, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 1, 0], [1, 1, 1, 0, 1, 0, 1, 0], [0, 0, 0, 0, 1, 0, 1, 0], [0, 0, 1, 0, 0, 0, 0, 0] ]; this.aStarInstance = new AStarFinder({ grid: { // 列主序矩阵 matrix: myMatrix } }); let startPos = { x: 0, y: 0 }; let goalPos = { x: 7, y: 7 }; let myPathway = this.aStarInstance.findPath(startPos, goalPos); console.log(myPathway); } } ``` -------------------------------- ### Get createapp Command Help Source: https://github.com/layabox/layaair-doc-zh/blob/LayaAir3.3/released/native/build_Cmd/readme.md Displays detailed help information and usage instructions for the createapp command. ```bash $ layanative3 createapp --help ``` -------------------------------- ### View createapp Command Help Source: https://github.com/layabox/layaair-doc-zh/blob/LayaAir3.3/_book/released/native/build_Cmd/readme.md Displays the help information for the createapp command, detailing its usage and available parameters for creating native projects. ```bash $ layanative3 createapp --help ``` -------------------------------- ### External JavaScript Module Example Source: https://github.com/layabox/layaair-doc-zh/blob/LayaAir3.3/2D/dom/readme.md This is an example of an external JavaScript file that can be dynamically loaded. It defines a class 'Demo1' with a 'start' method and logs a message to the console upon loading. This demonstrates how to structure modules for dynamic loading. ```javascript var Demo1 = (function () { function Client() { } Client.prototype.start = function () { // body... console.log("调用方法"); }; return Client; })(); console.log("我被加载进来了"); ``` -------------------------------- ### Example Usage Source: https://github.com/layabox/layaair-doc-zh/blob/LayaAir3.3/_book/released/native/platform_communication/readme.md Demonstrates how to set up message callbacks and send results in a C++ `main` function. ```APIDOC ## Message Handling Example ### Description This example shows how to implement the message handling callbacks and use `conchSendHandleMessageResult` to send data back to JavaScript. ### Code ```c int main(int argc, char *argv[]) { conchSetHandleMessageCallback( [](const char *eventName, const char *data) -> void { if (strcmp(eventName, "syncMessage") == 0) { conchSendHandleMessageResult(eventName, "sync message from platform"); } }, [](const char *eventName, const char *data) -> void { if (strcmp(eventName, "asyncMessage") == 0) { conchSendHandleMessageResult(eventName, "async message from platform"); } }); return conchMain(argc, argv); } ``` ``` -------------------------------- ### Access Base Layer and Default State Source: https://github.com/layabox/layaair-doc-zh/blob/LayaAir3.3/IDE/animationEditor/aniController/readme.md Example of how to get the BaseLayer AnimatorControllerLayer and its default animation state using code. ```typescript //获得BaseLayer层AnimatorControllerLayer let animatorControllerLayer : Laya.AnimatorControllerLayer = this.animator.getControllerLayer(0); //获得当前BaseLayer层的默认动画状态 let defaultState = animatorControllerLayer.defaultState; ``` -------------------------------- ### Example: Getting an Item from Pool Source: https://github.com/layabox/layaair-doc-zh/blob/LayaAir3.3/_book/basics/common/Pool/readme.md Demonstrates the basic usage of retrieving an object from the 'Bullet' pool. If 'null' is returned, it indicates the pool is empty. ```typescript let bullet = Pool.getItem("Bullet"); ``` -------------------------------- ### Full Project Directory Structure Example Source: https://github.com/layabox/layaair-doc-zh/blob/LayaAir3.3/_book/IDE/layapackage/exportToStore/readme.html An example of a complete project directory structure that can be zipped for export as a project source (template). This includes all potential directories, though not all are recommended for inclusion in a template. ```json LayaAirProject/ ├── .vscode/ │ └── settings.json │ └── launch.json ├── assets/ │ └── (项目资源) ├── bin/ │ ├── index.html │ └── (PC网页版调试运行目录) ├── engine/ │ └── (引擎声名文件与自定义引擎的目录) ├── library/ │ └── (IDE使用的项目临时存储目录) ├── local/ │ └── (IDE本地配置目录,例如IDE面板布局风格配置) ├── settings/ │ └── (项目的本地配置目录,例如构建发布的配置参数、层级配置、运行库引用配置) ├── src/ │ └── (项目源码) ├── tsconfig.json └── LayaAirProject.laya ``` -------------------------------- ### Example: Using getItemByCreateFun Source: https://github.com/layabox/layaair-doc-zh/blob/LayaAir3.3/_book/basics/common/Pool/readme.html Demonstrates using `getItemByCreateFun` to get a 'Bullet' object. If the pool is empty, a new 'Bullet' is created and optionally added back to the pool. ```typescript let bullet = Laya.Pool.getItemByCreateFun("Bullet", function() { // 创建一个子弹 let bullet = new Bullet(); // 拿到子弹的对象池 var pool = Laya.Pool.getPoolBySign("Bullet"); // 把子弹放入对象池,也可以不放入对象池,根据开发者需求 pool.push( bullet ); // 返回子弹对象 return bullet; }); ``` -------------------------------- ### Complete Build Target and Settings Example Source: https://github.com/layabox/layaair-doc-zh/blob/LayaAir3.3/IDE/layapackage/plug-in/readme.md This example demonstrates a full implementation of a custom build target, including registering types for settings, creating settings, and defining the build target with its inspector. The inspector panel is created using GUIUtils.createInspectorPanel and inspects the settings data. ```typescript @IEditor.panel("TestBuildSettings", { usage: "build-settings", title: "测试" }) export class TestBuildSettings extends IEditor.EditorPanel { @IEditor.onLoad static start() { Editor.typeRegistry.addTypes([ { name: "MyTestSettings2", catalogBarStyle : "hidden", properties: [ { name: "option1", type: "boolean", default: true }, { name: "option2", type: "string", default: "2332", } ] } ]); Editor.extensionManager.createSettings("MyBuildPlatformtSettings", "project"); Editor.extensionManager.createBuildTarget("test", { caption: "自定义平台", settingsName:"MyTestSettings2", inspector: "TestBuildSettings" }); } async create() { let panel = IEditor.GUIUtils.createInspectorPanel(); panel.allowUndo = true; panel.inspect(Editor.getSettings("MyBuildPlatformtSettings").data, "MyBuildPlatformtSettings"); this._panel = panel; } } ``` -------------------------------- ### Check Node.js Installation Source: https://github.com/layabox/layaair-doc-zh/blob/LayaAir3.3/_book/basics/developmentEnvironment/download/readme.md Verify if Node.js and npm are already installed by checking their help information. If you see command descriptions and version details, the environment is likely set up. ```bash npm -h ``` -------------------------------- ### Example: Accessing and Checking Bullet Pool Source: https://github.com/layabox/layaair-doc-zh/blob/LayaAir3.3/_book/basics/common/Pool/readme.md Demonstrates how to get a specific object pool (e.g., for bullets) and check its current size. If the pool is empty, it shows how to add a new object to it. ```typescript let bulletPool = Laya.Pool.getPoolBySign("Bullet"); // 查看当前对象池内对象数量 console.log( bulletPool.length ); if( bulletPool.length == 0 ) { // 把子弹放入对象池 pool.push( new Bullet() ); } ``` -------------------------------- ### Convert Grid Indices to Map Coordinates Source: https://github.com/layabox/layaair-doc-zh/blob/LayaAir3.3/3D/advanced/Astar/readme.md Example usage of `getGridIndex` to obtain grid indices for the start and end points of a path. It then retrieves the corresponding nodes from the A* graph's grid. ```typescript //调用getGridIndex方法,得到网格索引 this.getGridIndex(this.path[this.curPathIndex % this.pointCount].x, this.path[this.curPathIndex++ % this.pointCount].z, this.startPoint); this.getGridIndex(this.path[this.nextPathIndex % this.pointCount].x, this.path[this.nextPathIndex++ % this.pointCount].z, this.endPoint); //初始化start,end坐标点 var start = this.graph.grid[this.startPoint.x][this.startPoint.y]; var end = this.graph.grid[this.endPoint.x][this.endPoint.y]; ``` -------------------------------- ### Install Protobuf.js and ws Source: https://github.com/layabox/layaair-doc-zh/blob/LayaAir3.3/_book/libs/Protobuf/readme.html Installs the necessary Node.js modules for Protobuf communication and WebSocket handling. Run this command in your server's project directory. ```bash npm install protobufjs ws ``` -------------------------------- ### Log Network Type in LayaAir IDE Source: https://github.com/layabox/layaair-doc-zh/blob/LayaAir3.3/_book/released/native/network/readme.md Example of how to get and log the network type within the LayaAir IDE. This code snippet demonstrates integrating the network query into the `onStart` lifecycle method. ```typescript onStart(): void { var nType = (window as any).conch.config.getNetworkType(); console.log("network type: " + nType); } ``` -------------------------------- ### Create and Show GWindow Source: https://github.com/layabox/layaair-doc-zh/blob/LayaAir3.3/IDE/uiEditor/FairyGUI/GWindow/readme.md Instantiate a GWindow and set its content pane by loading a UI prefab. The window is then displayed using the show() method. ```TypeScript let win = new GWindow(); win.contentPane = ((await Laya.loader.load("Examples/windows/Window1.lh")) as Laya.Prefab).create(); window.show(); ``` -------------------------------- ### Create Node from Asset Source: https://github.com/layabox/layaair-doc-zh/blob/LayaAir3.3/_book/IDE/layapackage/plug-in/readme.html Implement logic to create a scene node from a specific asset type (e.g., 'png'). This example uses 'sharp' to get image metadata and creates a 'Sprite' node. ```typescript const sharp = IEditor.require("sharp"); class AssetHelper { @IEditor.onLoad onLoad() { console.log("AssetHelper onLoad"); Editor.extensionManager.addFileActions(["png"], { onCreateNode: async (asset) => { let imageMeta = await sharp(Editor.assetDb.getFullPath(asset)).metadata(); return Editor.scene.createNode("Sprite", { texture: { _$uuid: asset.id }, width: imageMeta.width, height: imageMeta.height }); } }); } } ``` -------------------------------- ### Build Web Project Source: https://github.com/layabox/layaair-doc-zh/blob/LayaAir3.3/_book/released/commandLine/readme.html Use this command to build your LayaAir project for the web platform. ```bash >LayaAirIDE --project=C:\Users\ASUS\Desktop\LayaProject --script=MyScript.buildWeb ```