### Complete Game Structure Initialization Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/api-reference/Scene.md Provides a comprehensive example of initializing a LayaAir game, including engine setup, creating game and UI scenes, and setting up the game loop. ```typescript class Game { gameScene: Scene; uiScene: Scene; async init() { // Initialize engine await Laya.init(800, 600); // Create scenes this.gameScene = this.createGameScene(); this.uiScene = this.createUIScene(); // Start game loop Laya.timer.frameLoop(1, this, this.update); } createGameScene(): Scene { let scene = new Scene(); scene.name = "GameScene"; // Add background let bg = new Sprite(); bg.name = "Background"; bg.size(800, 600); scene.addChild(bg); // Add player let player = new Sprite(); player.name = "Player"; player.x = 400; player.y = 500; scene.addChild(player); // Add enemies container let enemies = new Sprite(); enemies.name = "Enemies"; scene.addChild(enemies); Laya.stage.addChild(scene); return scene; } createUIScene(): Scene { let scene = new Scene(); scene.name = "UIScene"; // Add HUD let hud = new Sprite(); hud.name = "HUD"; scene.addChild(hud); // Add buttons let buttons = new Sprite(); buttons.name = "Buttons"; scene.addChild(buttons); Laya.stage.addChild(scene); return scene; } update() { // Game logic this.updateGameScene(); this.updateUIScene(); } updateGameScene() { let player = this.gameScene.getChild("Player"); if (player) { // Update player } } updateUIScene() { let hud = this.uiScene.getChild("HUD"); if (hud) { // Update UI } } } // Run let game = new Game(); game.init(); ``` -------------------------------- ### Stage Initialization Example Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/types.md Example of how to use the IStageConfig interface to initialize the LayaAir engine with specific stage settings. ```typescript let stageConfig: IStageConfig = { designWidth: 800, designHeight: 600, scaleMode: "showall", alignH: "center", alignV: "middle", backgroundColor: "#FFFFFF" }; await Laya.init(stageConfig); ``` -------------------------------- ### Install Engine Dependencies Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/README.md Run this command in the engine root directory to install project dependencies. ```bash npm install ``` -------------------------------- ### Complete Node Example Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/api-reference/Node.md A comprehensive example showcasing node creation, hierarchy management, component addition, event bubbling, and destruction. It demonstrates common usage patterns for the Node class. ```typescript // Create a node hierarchy let root = new Sprite(); root.name = "root"; let child1 = new Sprite(); child1.name = "child1"; root.addChild(child1); let child2 = new Sprite(); child2.name = "child2"; root.addChild(child2); let grandchild = new Sprite(); grandchild.name = "grandchild"; child1.addChild(grandchild); // Navigate the hierarchy console.log(root.numChildren); // 2 console.log(child1.parent.name); // "root" console.log(root.getChild("child1").name); // "child1" console.log(root.findChild("grandchild").name); // "grandchild" console.log(root.getChildByPath("child1.grandchild").name); // "grandchild" // Add component class MyComponent extends Component { onStart() { console.log("Component started"); } } let comp = child1.addComponent(MyComponent); // Event bubbling stage.addChild(root); stage.on("myEvent", () => { console.log("Event bubbled to stage"); }); grandchild.bubbleEvent("myEvent"); // Clean up root.destroy(true); // Destroys root and all descendants ``` -------------------------------- ### Complete Sprite Example with Interaction and Animation Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/api-reference/Sprite.md A full example demonstrating the initialization of the LayaAir engine, creation and configuration of a sprite, drawing graphics, adding it to the stage, and implementing click-based animation and continuous rotation. ```typescript // Initialize engine await Laya.init(800, 600); // Create a sprite let sprite = new Sprite(); sprite.size(100, 100); sprite.x = 350; sprite.y = 250; // Draw a gradient rectangle sprite.graphics.fillStyle = "#FF0000"; sprite.graphics.fillRect(0, 0, 100, 100); // Add to stage Laya.stage.addChild(sprite); // Add interaction sprite.mouseEnabled = true; sprite.on(Event.CLICK, () => { // Animate on click sprite.scaleX = 1.2; sprite.scaleY = 1.2; // Reset after 300ms Laya.timer.once(300, () => { sprite.scaleX = 1; sprite.scaleY = 1; }); }); // Rotate continuously Laya.timer.frameLoop(1, () => { sprite.rotation += 0.05; }); ``` -------------------------------- ### Basic LayaAir Configuration Setup Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/configuration.md Configure essential LayaAir settings like FPS, antialiasing, retina canvas, and default font before initializing the engine. This setup is suitable for general use cases. ```typescript import { Config } from "laya/Config"; // Configure before Laya.init() Config.FPS = 60; Config.isAntialias = true; Config.useRetinalCanvas = true; Config.defaultFont = "Arial"; Config.defaultFontSize = 14; // Then initialize await Laya.init(800, 600); ``` -------------------------------- ### Complete LayaAir Initialization Example Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/configuration.md This snippet demonstrates how to configure 2D, 3D, and stage settings, followed by the asynchronous initialization of the LayaAir engine. Ensure all necessary imports are included before use. ```typescript import { Laya } from "laya/Laya"; import { Config } from "laya/Config"; import { Config3D } from "laya/Config3D"; // Configure 2D Config.FPS = 60; Config.isAntialias = true; Config.defaultFont = "Arial"; Config.defaultFontSize = 14; // Configure 3D Config3D.enableMultiLight = true; Config3D.maxLightCount = 32; Config3D.pixelRatio = 1; // Configure stage let stageConfig = { designWidth: 800, designHeight: 600, scaleMode: "showall", alignH: "center", alignV: "middle" }; // Initialize engine async function init() { await Laya.init(stageConfig); console.log("Engine initialized"); } init(); ``` -------------------------------- ### Handler Example Usage Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/types.md Demonstrates creating and executing a Handler. The handler is set to execute only once. ```typescript let handler = new Handler(this, this.onComplete, ["success"], true); handler.run(); // Calls this.onComplete("success") once, then clears ``` -------------------------------- ### Complete Timer Example Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/api-reference/Timer.md Demonstrates setting up multiple frame-based and time-based timers, including update loops, enemy spawning, and progress saving. Also shows how to pause, resume, and clean up all timers. ```typescript class Game { constructor() { this.setupTimers(); } setupTimers() { // Update game state every frame Laya.timer.frameLoop(1, this, this.update); // Spawn enemies every 2 seconds Laya.timer.loop(2000, this, this.spawnEnemy); // Save progress every 30 seconds Laya.timer.loop(30000, this, this.saveProgress); } update() { // Called every frame (~60 times per second) this.updatePlayer(); this.updateEnemies(); } spawnEnemy() { console.log("Spawning enemy"); // Create new enemy } saveProgress() { console.log("Saving game"); // Save to localStorage } pause() { // Pause by setting scale to 0 Laya.timer.scale = 0; } resume() { // Resume normal speed Laya.timer.scale = 1; } destroy() { // Clean up all timers Laya.timer.clearAll(this); } } ``` -------------------------------- ### Scene Hierarchy Example Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/api-reference/Scene.md Illustrates a typical LayaAir game structure using nested Scenes and Sprites. This example shows how to create and add multiple scenes and child sprites to the stage. ```typescript // Stage (root) // ├── Scene (game scene) // │ ├── Background (Sprite) // │ ├── Player (Sprite) // │ └── Enemies (Container) // │ ├── Enemy1 (Sprite) // │ ├── Enemy2 (Sprite) // │ └── Enemy3 (Sprite) // └── UILayer (Scene) // ├── HUD (Sprite) // ├── Buttons (Container) // └── Dialogs (Container) let gameScene = new Scene(); gameScene.name = "GameScene"; Laya.stage.addChild(gameScene); let background = new Sprite(); background.name = "Background"; gameScene.addChild(background); let player = new Sprite(); player.name = "Player"; gameScene.addChild(player); let uiScene = new Scene(); uiScene.name = "UIScene"; Laya.stage.addChild(uiScene); ``` -------------------------------- ### Class Hierarchy Example Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/INDEX.md Illustrates the inheritance structure of key LayaAir classes, showing relationships between EventDispatcher, Node, Sprite, Stage, Scene, Loader, and Timer. ```plaintext EventDispatcher ├── Node │ ├── Sprite │ │ └── Stage │ └── Scene └── Loader Timer (singleton) Component (abstract) ``` -------------------------------- ### Basic 3D Setup Configuration Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/configuration.md Configure essential 3D rendering parameters like multi-light support, maximum light count, and pixel ratio before initializing LayaAir for a 3D scene. ```typescript import { Config3D } from "laya/Config3D"; // Configure before Laya.init() Config3D.enableMultiLight = true; Config3D.maxLightCount = 32; Config3D.pixelRatio = 1; await Laya.init(800, 600); ``` -------------------------------- ### Load Resources with LayaAir Loader Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/README.md Demonstrates loading single and multiple resources using Laya.loader. Includes an example of loading with progress updates. ```typescript // Load an image let texture = await Laya.loader.load("assets/image.png", Loader.IMAGE); // Load multiple resources let [bg, player, ui] = await Laya.loader.load([ "assets/background.png", "assets/player.png", "assets/ui.json" ]); // Load with progress let texture = await Laya.loader.load("assets/large.png", Loader.IMAGE, (progress) => { console.log("Loading: " + (progress * 100).toFixed(0) + "%"); } ); ``` -------------------------------- ### High-Performance Setup Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/configuration.md Configure LayaAir for high-end devices and 3D-heavy games by setting high FPS, enabling retinal canvas, and prioritizing high performance for WebGL. ```typescript // For high-end devices and 3D-heavy games Config.FPS = 120; Config.fixedFrames = true; Config.useRetinalCanvas = true; Config.powerPreference = "high-performance"; Config.enableUniformBufferObject = true; await Laya.init(1920, 1080); ``` -------------------------------- ### Attaching Components to Scenes Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/api-reference/Scene.md Demonstrates how to attach custom behavior components to a scene using `addComponent`. The `GameLogic` component example includes `onStart`, `onUpdate`, and `onDestroy` methods for managing game logic. ```typescript class GameLogic extends Component { owner: Scene; onStart() { console.log("Game logic started"); } onUpdate() { // Game logic each frame } onDestroy() { console.log("Game logic destroyed"); } } let scene = new Scene(); let logic = scene.addComponent(GameLogic); Laya.stage.addChild(scene); ``` -------------------------------- ### Destroy Node Example Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/api-reference/Node.md Demonstrates how to destroy a node and optionally its children. Ensure the node is no longer used after destruction. ```typescript let node = new Sprite(); stage.addChild(node); // Later, destroy it node.destroy(true); // Also destroys children // node is no longer usable after this ``` -------------------------------- ### Example of Event Bubbling Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/api-reference/Node.md Demonstrates how to dispatch and listen for a custom event that bubbles up the node hierarchy. An event listener is set on the stage. ```typescript // Bubble a custom event up the hierarchy let node = new Sprite(); stage.addChild(node); stage.on("customEvent", (data) => { console.log("Event received:", data); }); node.bubbleEvent("customEvent", { message: "hello" }); ``` -------------------------------- ### Transparent Canvas Setup Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/configuration.md Enable a transparent background for the canvas, which is useful for embedding LayaAir content within other web pages or applications. ```typescript // For transparent background (useful for embedding) Config.isAlpha = true; Config.premultipliedAlpha = true; await Laya.init(800, 600); // Canvas now has transparent background ``` -------------------------------- ### Add Components to Nodes in LayaAir Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/README.md Explains how to attach custom components to display objects to add behavior. Includes examples of component lifecycle methods. ```typescript class PlayerController extends Component { onStart() { // Initialize } onUpdate() { // Called every frame } onDestroy() { // Cleanup } } let player = new Sprite(); let controller = player.addComponent(PlayerController); ``` -------------------------------- ### Mouse Drag Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/api-reference/Event.md Provides examples for handling mouse drag events, including `MOUSE_DRAG` for continuous dragging and `MOUSE_DRAG_END` for when the drag operation finishes. This is useful for implementing draggable UI elements. ```APIDOC ### Mouse Drag ```typescript let sprite = new Sprite(); sprite.mouseEnabled = true; sprite.size(100, 100); stage.addChild(sprite); sprite.on(Event.MOUSE_DRAG, () => { // Update position while dragging console.log("Dragging at:", Laya.stage.mouseX, Laya.stage.mouseY); }); sprite.on(Event.MOUSE_DRAG_END, () => { console.log("Drag ended"); }); ``` ``` -------------------------------- ### Applying Transformations to a Sprite Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/api-reference/Sprite.md Provides examples of common transformations including rotation, scaling, setting pivot points, and adjusting transparency (alpha). Anchor points offer a convenient way to set pivot relative to sprite dimensions. ```typescript // Rotate 45 degrees sprite.rotation = Math.PI / 4; // Scale to 1.5x sprite.scaleX = 1.5; sprite.scaleY = 1.5; // Set pivot point at center sprite.pivotX = sprite.width / 2; sprite.pivotY = sprite.height / 2; // Or use anchor (0-1 range) sprite.anchorX = 0.5; sprite.anchorY = 0.5; // Fade in sprite.alpha = 0.5; // 50% transparent ``` -------------------------------- ### Scene Performance Optimization with Object Pooling Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/api-reference/Scene.md Provides an example of optimizing scene performance by implementing object pooling for frequently created and destroyed objects like enemies. This reduces garbage collection overhead and improves frame rates. ```typescript class OptimizedScene extends Scene { // Use object pooling for frequently created objects enemyPool: Array = []; createEnemy() { let enemy = this.enemyPool.length > 0 ? this.enemyPool.pop() : new Enemy(); this.addChild(enemy); return enemy; } destroyEnemy(enemy: Enemy) { this.removeChild(enemy); this.enemyPool.push(enemy); } // Clean up unused resources cleanup() { // Remove all children while (this.numChildren > 0) { this.removeChildAt(0); } // Clear pool this.enemyPool.length = 0; } } ``` -------------------------------- ### Stage Initialization and Configuration Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/api-reference/Stage.md Demonstrates basic initialization of the LayaAir engine and configuration of the stage properties such as scaling, alignment, and frame rate. ```APIDOC ## Stage Initialization and Configuration ### Description Initializes the LayaAir engine and configures the stage's display properties. ### Usage ```typescript // Basic initialization and setup await Laya.init(800, 600); // Access the stage let stage = Laya.stage; // Configure scaling and alignment stage.scaleMode = Stage.SCALE_SHOWALLALL; stage.alignH = Stage.ALIGN_CENTER; stage.alignV = Stage.ALIGN_MIDDLE; // Control frame rate stage.frameMode = Stage.FRAME_MOUSE; // Pause rendering stage.renderingEnabled = false; // Resume rendering stage.renderingEnabled = true; ``` ### Properties - **scaleMode** (string) - Sets the scaling mode for the stage. - **alignH** (string) - Sets the horizontal alignment for the stage. - **alignV** (string) - Sets the vertical alignment for the stage. - **frameMode** (string) - Controls the frame rate behavior. - **renderingEnabled** (boolean) - Enables or disables rendering. ``` -------------------------------- ### Initialize and Configure LayaAir Stage Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/api-reference/Stage.md Demonstrates basic initialization of LayaAir, accessing the stage, and configuring its scaling mode, horizontal and vertical alignment. It also shows how to add a sprite to the stage and listen for resize events. ```typescript await Laya.init(800, 600); let stage = Laya.stage; stage.scaleMode = Stage.SCALE_SHOWALLALL; stage.alignH = Stage.ALIGN_CENTER; stage.alignV = Stage.ALIGN_MIDDLE; let sprite = new Sprite(); sprite.x = 100; sprite.y = 100; stage.addChild(sprite); stage.on(Event.RESIZE, () => { console.log("Stage resized to:", stage.width, stage.height); }); stage.frameMode = Stage.FRAME_MOUSE; stage.renderingEnabled = false; stage.renderingEnabled = true; ``` -------------------------------- ### TextureFormat Enum Definition Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/types.md Specifies the pixel format for textures, with examples like R8G8B8A8 and R16G16B16A16. ```typescript enum TextureFormat { R8G8B8A8 = 0, R16G16B16A16 = 1, R32G32B32A32 = 2, // ... many more formats } ``` -------------------------------- ### Get Direct Child by Name Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/api-reference/Node.md Retrieves a direct child node by its name. This method is equivalent to getChildByName. ```typescript getChild(name: string): Node ``` -------------------------------- ### Laya3D Initialization via Laya.init() Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/api-reference/Laya3D.md Demonstrates that Laya.init() automatically handles Laya3D initialization, making 3D features available. ```typescript // Laya.init() automatically initializes Laya3D await Laya.init(800, 600); // 3D features are now available let scene = new Scene3D(); ``` -------------------------------- ### Get Cached Resource Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/api-reference/Loader.md Retrieve a resource that has already been loaded and cached. This is useful for accessing assets without re-downloading them. ```typescript // Load a resource await Laya.loader.load("assets/texture.png", Loader.IMAGE); // Get it from cache later let cachedTexture = Laya.loader.getRes("assets/texture.png"); ``` -------------------------------- ### Get Direct Child by Name (Alias) Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/api-reference/Node.md Retrieves a direct child node by its name. This method is equivalent to getChild. ```typescript getChildByName(name: string): Node ``` -------------------------------- ### Creating and Adding a Scene Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/api-reference/Scene.md Demonstrates how to instantiate a new Scene object, assign it a name, and add it to the LayaAir stage. ```typescript // Create a new scene let scene = new Scene(); scene.name = "MainScene"; // Add to stage Laya.stage.addChild(scene); ``` -------------------------------- ### Get All Resources in a Group Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/api-reference/Loader.md Retrieve all resources that were loaded and assigned to a specific group. This is helpful for managing and accessing related assets. ```typescript // Load multiple resources in a group await Laya.loader.load([ { url: "assets/ui1.png", group: "UI" }, { url: "assets/ui2.png", group: "UI" }, { url: "assets/ui3.png", group: "UI" } ]); // Get all UI resources let uiResources = Laya.loader.getGroupRes("UI"); console.log("UI resources count:", uiResources.length); ``` -------------------------------- ### Create a Basic 3D Scene Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/api-reference/Laya3D.md Shows how to create a 3D scene, add a sprite with a mesh renderer, and a camera after initialization. ```typescript // Create a 3D scene let scene = new Scene3D(); // Create 3D sprite let sprite3D = new Sprite3D(); sprite3D.addComponent(MeshRenderer); scene.addChild(sprite3D); // Create camera let camera = new Camera(); scene.addChild(camera); // Add to stage Laya.stage.addChild(scene); ``` -------------------------------- ### Get Component from Node Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/api-reference/Node.md Retrieves a component instance of a specified class from the node. Returns null if no component of that type is found. ```typescript getComponent(type: new (...args: any[]) => T): T ``` -------------------------------- ### Get Child Index Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/api-reference/Node.md Retrieves the index of a specific child node within its parent. Returns -1 if the node is not found. ```typescript getChildIndex(node: Node): number ``` -------------------------------- ### Laya.addInitCallback Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/api-reference/Laya.md Adds an initialization callback that executes in parallel during engine initialization. This is useful for modules like physics that need to register their initialization logic. ```APIDOC ## Laya.addInitCallback ### Description Adds an initialization callback that executes in parallel during engine initialization. This is useful for modules like physics that need to register their initialization logic. ### Method `static addInitCallback(callback: () => void | Promise): void` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **callback** (() => void | Promise) - Required - The initialization function to execute. Can be asynchronous. ### Request Example ```typescript Laya.addInitCallback(() => { console.log("Engine initialization callback"); // Initialize custom modules }); ``` ### Response #### Success Response (200) `void` #### Response Example None provided. ``` -------------------------------- ### Get Child by Index Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/api-reference/Node.md Retrieves a direct child node using its index in the children array. Returns null if the index is out of bounds. ```typescript getChildAt(index: number): Node ``` -------------------------------- ### Laya.addBeforeInitCallback Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/api-reference/Laya.md Executes custom logic before engine initialization. At this point, the Stage has not been created yet, allowing you to dynamically modify the stage configuration. ```APIDOC ## Laya.addBeforeInitCallback ### Description Executes custom logic before engine initialization. At this point, the Stage has not been created yet, allowing you to dynamically modify the stage configuration. ### Method `static addBeforeInitCallback(callback: (stageConfig: IStageConfig) => void | Promise): void` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **callback** ((stageConfig: IStageConfig) => void | Promise) - Required - Callback function that receives the stage configuration. Executed in registration order. ### Request Example ```typescript Laya.addBeforeInitCallback((stageConfig) => { // Dynamically set stage configuration stageConfig.designWidth = window.innerWidth; stageConfig.designHeight = window.innerHeight; stageConfig.scaleMode = "full"; }); Laya.init(800, 600); ``` ### Response #### Success Response (200) `void` #### Response Example None provided. ``` -------------------------------- ### Run Engine Tests Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/README.md Execute tests for the LayaAir engine from the repository root directory. Ensure to open bin/index.html with a live server afterward. ```bash npm run start ``` -------------------------------- ### Basic Event Listening Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/api-reference/Event.md Demonstrates how to listen for and dispatch events on a Sprite object. This includes adding listeners using `on()`, specifying the event type and a callback function, and removing listeners using `off()`. ```APIDOC ### Basic Event Listening ```typescript let sprite = new Sprite(); sprite.mouseEnabled = true; stage.addChild(sprite); // Listen to click event sprite.on(Event.CLICK, (ev: Event) => { console.log("Sprite clicked!"); }); // Listen with callback function function onMouseDown(ev: Event) { console.log("Mouse down on:", ev.target); } sprite.on(Event.MOUSE_DOWN, onMouseDown); // Remove listener sprite.off(Event.MOUSE_DOWN, onMouseDown); ``` ``` -------------------------------- ### Performance Considerations Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/api-reference/Scene.md Tips for optimizing scene performance, including using object pooling for frequently created objects and cleaning up unused resources. ```APIDOC ## Performance Considerations Best practices for maintaining good performance with scenes. ### Object Pooling For objects that are frequently created and destroyed (e.g., enemies, bullets), use an object pool to reuse instances instead of constantly allocating and deallocating memory. ### Resource Cleanup Ensure that all resources, such as child objects and temporary data structures, are properly cleaned up when they are no longer needed to prevent memory leaks. ### Example: Optimized Scene ```typescript class OptimizedScene extends Scene { // Use object pooling for frequently created objects enemyPool: Array = []; createEnemy() { let enemy = this.enemyPool.length > 0 ? this.enemyPool.pop() : new Enemy(); this.addChild(enemy); return enemy; } destroyEnemy(enemy: Enemy) { this.removeChild(enemy); this.enemyPool.push(enemy); } // Clean up unused resources cleanup() { // Remove all children while (this.numChildren > 0) { this.removeChildAt(0); } // Clear pool this.enemyPool.length = 0; } } ``` ``` -------------------------------- ### Get Descendant Node by Path Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/api-reference/Node.md Finds a descendant node by specifying its path using dot notation (e.g., 'parent.child.grandchild'). Returns null if the path is not found. ```typescript getChildByPath(path: string): Node ``` -------------------------------- ### Scene Lifecycle Methods Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/api-reference/Scene.md Demonstrates the lifecycle methods of a Scene, including onAdded, initScene, onDisplay, onUndisplay, onRemoved, cleanup, and onDestroy. These methods are called automatically based on the scene's state changes. ```APIDOC ## Scene Lifecycle This section covers the core lifecycle methods available for `Scene` objects. These methods are invoked automatically by the LayaAir engine during various stages of a scene's existence. ### Methods - **`constructor()`**: Initializes a new instance of the `GameScene`. - **`onAdded()`**: Called when the scene is added to a parent node. Use this for initial setup. - **`initScene()`**: A custom method to initialize the scene's content and components. - **`onDisplay()`**: Called when the scene becomes visible in the display list. - **`onUndisplay()`**: Called when the scene is removed from the display list (hidden). - **`onRemoved()`**: Called when the scene is removed from its parent node. Use this for cleanup before removal. - **`cleanup()`**: A custom method to perform resource cleanup. - **`onDestroy()`**: Called when the scene is destroyed and its resources are released. ### Usage Example ```typescript class GameScene extends Scene { constructor() { super(); this.name = "GameScene"; } onAdded() { console.log("Scene added to parent"); this.initScene(); } initScene() { let player = new Sprite(); this.addChild(player); this.addComponent(GameLogic); } onDisplay() { console.log("Scene displayed"); } onUndisplay() { console.log("Scene hidden"); } onRemoved() { console.log("Scene removed from parent"); this.cleanup(); } cleanup() { this.clearAllChildren(); } onDestroy() { console.log("Scene destroyed"); } } let scene = new GameScene(); Laya.stage.addChild(scene); // Calls onAdded and onDisplay Laya.stage.removeChild(scene); // Calls onUndisplay and onRemoved scene.destroy(); // Calls onDestroy ``` ``` -------------------------------- ### Laya.init Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/api-reference/Laya.md Initializes the LayaAir engine. This method must be called before using any other engine features. It can be initialized using either design width and height or a configuration object. ```APIDOC ## Laya.init ### Description Initializes the LayaAir engine. This method must be called before using any other engine features. It can be initialized using either design width and height or a configuration object. ### Method `static init(stageConfig?: IStageConfig): Promise` `static init(width: number, height: number): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **stageConfig** (IStageConfig) - Optional - Configuration object for stage initialization. If not provided, width and height parameters are used instead. - **width** (number) - Optional - Design width of the game window. Only used if stageConfig is not provided. - **height** (number) - Optional - Design height of the game window. Only used if stageConfig is not provided. ### Request Example ```typescript // Method 1: Using design width and height await Laya.init(800, 600); // Method 2: Using configuration object await Laya.init({ designWidth: 800, designHeight: 600, scaleMode: "showAll", alignH: "center", alignV: "middle" }); // Method 3: Using async/await async function initGame() { await Laya.init(800, 600); // Now you can use Laya.stage and other engine features let sprite = new Sprite(); Laya.stage.addChild(sprite); } initGame(); ``` ### Response #### Success Response (200) `Promise` - A promise that resolves when initialization is complete. #### Response Example None provided. ``` -------------------------------- ### Loading Events Usage Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/api-reference/Event.md Demonstrates how to use loading events like `COMPLETE` and `ERROR` with the `Laya.loader`. This is essential for managing the loading of external resources and handling potential loading failures. ```APIDOC ### Loading Events ```typescript let loader = Laya.loader; loader.on(Event.COMPLETE, (url: string) => { console.log("Loading complete:", url); }); loader.on(Event.ERROR, (url: string) => { console.log("Loading error:", url); }); loader.load("path/to/resource.png"); ``` ``` -------------------------------- ### Dynamic Runtime Configuration Changes Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/configuration.md Demonstrates how to dynamically change certain LayaAir settings at runtime, such as frame rate, timer scale for slow motion, and rendering enabled status. ```typescript // Change FPS at runtime Laya.stage.frameMode = Stage.FRAME_SLOW; // Reduce frame rate // Change timer scale Laya.timer.scale = 0.5; // Slow motion // Change rendering enabled Laya.stage.renderingEnabled = false; // Pause rendering // But most Config properties should be set before init ``` -------------------------------- ### Stage Events Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/api-reference/Event.md Shows how to listen for stage-level events like `RESIZE`, `FOCUS`, and `BLUR`. These events are useful for responding to global changes in the application's display area and focus state. ```APIDOC ### Stage Events ```typescript Laya.stage.on(Event.RESIZE, () => { console.log("Stage resized to:", Laya.stage.width, Laya.stage.height); }); Laya.stage.on(Event.FOCUS, () => { console.log("Stage gained focus"); }); Laya.stage.on(Event.BLUR, () => { console.log("Stage lost focus"); }); ``` ``` -------------------------------- ### Enable 3D Physics Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/api-reference/Laya3D.md Sets the physics creation utility to enable 3D physics. Ensure PhysicsUtil3D is imported. ```typescript // Enable 3D physics import { PhysicsUtil3D } from "laya/Physics3D/PhysicsUtil3D"; let physicsUtil = new PhysicsUtil3D(); Laya3D.PhysicsCreateUtil = physicsUtil; // Now Laya3D.enablePhysics will be true console.log(Laya3D.enablePhysics); // true ``` -------------------------------- ### Add Callback Before Engine Initialization Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/api-reference/Laya.md Registers a callback function to be executed before the LayaAir engine starts its main initialization. This allows for dynamic modification of the stage configuration before the Stage object is created. The callback receives the stage configuration object. ```typescript Laya.addBeforeInitCallback((stageConfig) => { // Dynamically set stage configuration stageConfig.designWidth = window.innerWidth; stageConfig.designHeight = window.innerHeight; stageConfig.scaleMode = "full"; }); Laya.init(800, 600); ``` -------------------------------- ### Schedule Tasks with LayaAir Timer Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/README.md Shows how to schedule tasks to run once, in a loop, or every frame using Laya.timer. Includes clearing scheduled timers. ```typescript // Execute once after 1 second Laya.timer.once(1000, this, () => { console.log("1 second passed"); }); // Execute every 16ms (game loop) Laya.timer.loop(16, this, this.update); // Execute every frame Laya.timer.frameLoop(1, this, this.update); // Clear timer Laya.timer.clear(this, this.update); ``` -------------------------------- ### Build LayaAir Engine Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/README.md Compile the LayaAir engine from the root directory. This command generates a build folder containing the compiled engine files. ```bash npm run build ``` -------------------------------- ### Configure 3D Rendering Settings Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/api-reference/Laya3D.md Configures various 3D rendering options using Config3D before engine initialization. Import Config3D. ```typescript import { Config3D } from "laya/Config3D"; // Configure 3D rendering Config3D.enableDynamicBatch = true; Config3D.enableStaticBatch = true; Config3D.pixelRatio = 1; Config3D.enableMultiLight = true; Config3D.maxLightCount = 32; // Then initialize await Laya.init(800, 600); ``` -------------------------------- ### addAfterInitCallback Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/api-reference/Laya.md Executes custom logic after the engine has finished its initialization process. Registered callbacks are executed in the order they were added. ```APIDOC ## addAfterInitCallback ### Description Executes custom logic after engine initialization. All registered callbacks are executed in registration order. ### Method static ### Signature ```typescript static addAfterInitCallback(callback: () => void | Promise): void ``` ### Parameters #### Path Parameters - callback ( () => void | Promise ) - Required - Callback function to execute after initialization. Can be asynchronous. ### Returns `void` ### Example ```typescript Laya.addAfterInitCallback(() => { console.log("Engine initialization complete"); // Load initial scene or assets }); ``` ``` -------------------------------- ### Handle Events in LayaAir Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/README.md Demonstrates listening for and dispatching events within the LayaAir event system. Includes common event types and how to stop listening. ```typescript // Listen to events sprite.on(Event.CLICK, (ev: Event) => { console.log("Clicked!"); }); // Dispatch custom events node.bubbleEvent("customEvent", { data: "hello" }); // Stop listening sprite.off(Event.CLICK, callback); ``` -------------------------------- ### Stage Initialization Configuration Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/types.md Defines the configuration object for initializing the LayaAir stage, including design dimensions, scaling, alignment, and background color. ```typescript interface IStageConfig { /** * Design width of the stage in pixels */ designWidth: number; /** * Design height of the stage in pixels */ designHeight: number; /** * Scale mode for screen adaptation * Possible values: "noscale" | "showall" | "noborder" | "full" | "fixedwidth" | "fixedheight" | "fixedauto" */ scaleMode?: string; /** * Screen orientation mode * Possible values: "none" | "horizontal" | "vertical" */ screenMode?: string; /** * Horizontal alignment of canvas * Possible values: "left" | "center" | "right" */ alignH?: string; /** * Vertical alignment of canvas * Possible values: "top" | "middle" | "bottom" */ alignV?: string; /** * Background color as hex string (e.g., "#FFFFFF") */ backgroundColor?: string; } ``` -------------------------------- ### Initialize Laya Engine Before Accessing Stage Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/errors.md Shows the correct way to access Laya.stage by ensuring Laya.init() is called first. Accessing Laya.stage before initialization will result in null. ```typescript // ERROR: Using Laya.stage before init let stage = Laya.stage; // Returns null! // CORRECT: Initialize first await Laya.init(800, 600); let stage = Laya.stage; // Now valid // Or check initialization if (Laya.stage) { // Safe to use } ``` -------------------------------- ### IStageConfig Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/types.md Configuration object for initializing the LayaAir stage, including design dimensions, scaling, alignment, and background color. ```APIDOC ## IStageConfig ### Description Stage initialization configuration object. ### Interface ```typescript interface IStageConfig { /** * Design width of the stage in pixels */ designWidth: number; /** * Design height of the stage in pixels */ designHeight: number; /** * Scale mode for screen adaptation * Possible values: "noscale" | "showall" | "noborder" | "full" | "fixedwidth" | "fixedheight" | "fixedauto" */ scaleMode?: string; /** * Screen orientation mode * Possible values: "none" | "horizontal" | "vertical" */ screenMode?: string; /** * Horizontal alignment of canvas * Possible values: "left" | "center" | "right" */ alignH?: string; /** * Vertical alignment of canvas * Possible values: "top" | "middle" | "bottom" */ alignV?: string; /** * Background color as hex string (e.g., "#FFFFFF") */ backgroundColor?: string; } ``` ### Example ```typescript let stageConfig: IStageConfig = { designWidth: 800, designHeight: 600, scaleMode: "showall", alignH: "center", alignV: "middle", backgroundColor: "#FFFFFF" }; await Laya.init(stageConfig); ``` ``` -------------------------------- ### Configure LayaAir Engine Settings Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/README.md Set engine configurations for 2D and 3D before initialization. This includes FPS, anti-aliasing, default font, multi-light settings, and max light count. ```typescript import { Config } from "laya/Config"; import { Config3D } from "laya/Config3D"; // 2D configuration Config.FPS = 60; Config.isAntialias = true; Config.defaultFont = "Arial"; // 3D configuration Config3D.enableMultiLight = true; Config3D.maxLightCount = 32; Config3D.pixelRatio = 1; // Initialize await Laya.init(800, 600); ``` -------------------------------- ### load Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/api-reference/Loader.md Loads resources with advanced options, supporting single or multiple URLs, custom loading options, and progress callbacks. ```APIDOC ## load ### Description Loads resources with advanced options, supporting single or multiple URLs, custom loading options, and progress callbacks. ### Method Signature ```typescript load(url: string | ILoadURL | ILoadURL[], options?: ILoadOptions, onProgress?: ProgressCallback): Promise ``` ### Parameters #### Path Parameters - **url** (string | ILoadURL | ILoadURL[]) - Required - URL or array of URLs. - **options** (ILoadOptions) - Optional - Loading options object. - **onProgress** (ProgressCallback) - Optional - Progress callback function. ### LoadOptions Properties #### Path Parameters - **type** (string) - Optional - Resource type. - **priority** (number) - Optional - Loading priority (higher = more important). Default: 0. - **group** (string) - Optional - Resource group name for collective management. - **cache** (boolean) - Optional - Whether to cache the loaded resource. Default: true. - **ignoreCache** (boolean) - Optional - Whether to bypass cache and reload. Default: false. - **noRetry** (boolean) - Optional - Whether to skip retry on failure. Default: false. - **silent** (boolean) - Optional - Whether to suppress error console messages. Default: false. - **useWorkerLoader** (boolean) - Optional - Whether to use worker for loading (IMAGE only). Default: false. ### Request Example ```typescript let options = { type: Loader.IMAGE, priority: 10, group: "UI", cache: true }; let texture = await Laya.loader.load("assets/ui/button.png", options); ``` ``` -------------------------------- ### Stage and UI Events Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/api-reference/Event.md This section details various stage and UI events that can be triggered, such as RESIZE, FOCUS, BLUR, and VISIBILITY_CHANGE. These events are crucial for handling user interactions and application state changes. ```APIDOC ## Stage and UI Events | Event | Value | Description | |---|---|---| | RESIZE | "resize" | Triggered when stage size changes. | | WILL_RESIZE | "willResize" | Triggered before stage resize. | | FOCUS | "focus" | Triggered when stage gains focus. | | BLUR | "blur" | Triggered when stage loses focus. | | FOCUS_CHANGE | "focuschange" | Triggered when focus changes. | | VISIBILITY_CHANGE | "visibilitychange" | Triggered when visibility changes. | | FULL_SCREEN_CHANGE | "fullscreenchange" | Triggered on fullscreen change. | | CHANGE | "change" | Triggered when value changes. | | CHANGED | "changed" | Triggered after value has changed. | | MOVED | "moved" | Triggered when position changes. | ``` -------------------------------- ### Sprite Event Handling Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/api-reference/Sprite.md Demonstrates how to enable mouse events and attach listeners for various interaction types like clicks, mouse down, and mouse move on a Sprite object. ```APIDOC ## Sprite Event Handling ### Description This section shows how to enable and listen for various mouse events on a Sprite object. This allows for interactive elements within your application. ### Methods - `mouseEnabled = true` - Enables mouse interaction for the sprite. - `on(eventType, handler)` - Attaches an event listener to the sprite. ### Event Types - `Event.CLICK`: Triggered when the sprite is clicked. - `Event.MOUSE_DOWN`: Triggered when the mouse button is pressed down over the sprite. - `Event.MOUSE_MOVE`: Triggered when the mouse pointer moves over the sprite. ### Example Usage ```typescript // Listen to mouse events sprite.mouseEnabled = true; sprite.on(Event.CLICK, (ev: Event) => { console.log("Sprite clicked!"); }); // Listen to input events sprite.on(Event.MOUSE_DOWN, () => { console.log("Mouse down"); }); sprite.on(Event.MOUSE_MOVE, () => { console.log("Mouse move"); }); ``` ``` -------------------------------- ### Scene Event Handling Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/api-reference/Scene.md Listen for various scene-related events such as child addition/removal and display/undisplay states using the `on()` method. ```APIDOC ## Scene Events Subscribe to events emitted by the scene. ### Methods - **`on(type: string, listener: Function, once?: boolean)`**: Registers an event listener. - **`off(type: string, listener?: Function)`**: Removes an event listener. ### Event Types - **`Event.ADDED`**: Fired when a child is added to the scene. - **`Event.REMOVED`**: Fired when a child is removed from the scene. - **`Event.DISPLAY`**: Fired when the scene is added to the display list and becomes visible. - **`Event.UNDISPLAY`**: Fired when the scene is removed from the display list and becomes hidden. ### Usage Example ```typescript let scene = new Scene(); // Listen to child addition scene.on(Event.ADDED, () => { console.log("Child added to scene"); }); // Listen to child removal scene.on(Event.REMOVED, () => { console.log("Child removed from scene"); }); // Listen to display events scene.on(Event.DISPLAY, () => { console.log("Scene is now displayed"); }); scene.on(Event.UNDISPLAY, () => { console.log("Scene is now hidden"); }); Laya.stage.addChild(scene); ``` ``` -------------------------------- ### Keyboard Events Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/api-reference/Event.md Details how to handle keyboard events like `KEY_DOWN` and `KEY_UP` on the stage. It shows how to access key codes and perform actions based on key presses. ```APIDOC ### Keyboard Events ```typescript Laya.stage.on(Event.KEY_DOWN, (ev: Event) => { console.log("Key code:", ev.data); if (ev.data === 32) { // Space key console.log("Space pressed!"); } }); Laya.stage.on(Event.KEY_UP, () => { console.log("Key released"); }); ``` ``` -------------------------------- ### Component Source: https://github.com/layabox/layaair/blob/LayaAir_3.3/_autodocs/types.md Base class for all components in LayaAir, providing lifecycle methods like onStart, onEnable, onDisable, onDestroy, onUpdate, and onLateUpdate. ```APIDOC ## Component Base Class ### Description Base class for all components in LayaAir. ### Class ```typescript abstract class Component extends EventDispatcher { /** * The owner node of this component */ owner: Node; /** * Whether the component is enabled */ enabled: boolean; /** * Called when the component is initialized */ onStart(): void; /** * Called when the component is enabled */ onEnable(): void; /** * Called when the component is disabled */ onDisable(): void; /** * Called when the owner node is destroyed */ onDestroy(): void; /** * Called each frame */ onUpdate(): void; /** * Called for late update each frame */ onLateUpdate(): void; } ``` ```