SuperAPI AI Directory

layaair-2x-cn

Coding & development

View repository

Updated 10-16 09:31

About this skill

LayaAir 2.0 Development Standards

⚠️ LayaAir 2.0(TypeScript): All patterns and examples are compatible with LayaAir 2.x versions (2.0+).

Official Documentation:https://ldc2.layabox.com/doc/?nav=zh-ts-0-3-0 API Reference:https://ldc2.layabox.com/api/


Skill Purpose

This skill provides comprehensive development standards guidance for LayaAir 2.0 projects (TypeScript strict mode preferred):

Priority 1: Code Quality and Standards

  • TypeScript strict typing, access modifiers (public/private/protected)
  • Exception handling (do not silently swallow errors)
  • console.log for development environment only
  • Correct event registration/deregistration pairing

Priority 2: LayaAir 2.0 Architecture

  • Script/Component system:onAwake → onEnable → onStart → onUpdate → onLateUpdate → onDisable → onDestroy
  • Event system:EventDispatcher.on/off/dispatch、Laya.stage global events
  • Resource management:Laya.loader.load()、Laya.loader.getRes(), resource release
  • Tween easing:Laya.Tween.to/from/clearAll
  • Timer timers:Laya.timer.loop/once/clearAll
  • UI system: IDE-generated UI classes, Scene loading

Priority 3: Performance and Playable Ads Optimization

  • DrawCall optimization, atlas merging, CacheAs static caching
  • onUpdate zero memory allocation
  • Package size <5MB strategy

Quick Reference Guide

Task Reference Documentation
Script components, lifecycle Display and component system
EventDispatcher, event listeners Event patterns
Resource loading, release Resource management
Tween easing, Timer timers Easing and animation
TypeScript code standards Quality and standards
DrawCall optimization, performance Performance optimization
Architecture review checklist Architecture review
Code quality review Quality review

⚡ Quick API Reference

Engine initialization

// 标准初始化(WebGL 模式,可回退 Canvas)
Laya.init(750, 1334, Laya.WebGL);
Laya.stage.alignV = "top";
Laya.stage.alignH = "left";
Laya.stage.scaleMode = "showall";
Laya.stage.bgColor = "#000000";

Script components (2.0 core feature)

class PlayerScript extends Laya.Script {
    /** @prop {name: speed, tips:"移动速度", type: Number, default: 5} */
    public speed: number = 5;

    private _owner: Laya.Sprite;

    public onAwake(): void {
        // 组件激活,owner 已就绪(等同 Awake)
        this._owner = this.owner as Laya.Sprite;
    }

    public onStart(): void {
        // 第一帧 Update 执行前(等同 Start)
    }

    public onEnable(): void {
        // 组件启用时(注册事件在此)
        Laya.stage.on(Laya.Event.CLICK, this, this.onClick);
    }

    public onUpdate(): void {
        // 每帧调用(等同 Update)
        this.owner.x += this.speed;
    }

    public onLateUpdate(): void {
        // 每帧 onUpdate 之后(等同 LateUpdate)
    }

    public onDisable(): void {
        // 组件禁用时(注销事件在此)
        Laya.stage.off(Laya.Event.CLICK, this, this.onClick);
    }

    public onDestroy(): void {
        // 组件销毁时(清理资源)
    }

    private onClick(e: Laya.Event): void {
        // 处理点击
    }
}

Nodes and display objects

// 创建 Sprite
const sp = new Laya.Sprite();
Laya.stage.addChild(sp);
sp.pos(100, 200);
sp.size(200, 100);

// 加载并显示图片
sp.loadImage("res/img/bg.png");

// 文本
const txt = new Laya.Text();
txt.text = "Hello LayaAir 2.0";
txt.color = "#ffffff";
txt.fontSize = 30;
Laya.stage.addChild(txt);

// 节点层级
parent.addChild(child);
parent.removeChild(child);
child.removeSelf();
sp.destroy(true); // true=递归销毁子节点

Event system

// 注册事件
node.on(Laya.Event.CLICK, this, this.onClick);
node.once(Laya.Event.CLICK, this, this.onClick); // 只触发一次
Laya.stage.on(Laya.Event.RESIZE, this, this.onResize);

// 注销事件
node.off(Laya.Event.CLICK, this, this.onClick);
node.offAll(Laya.Event.CLICK); // 注销该事件所有监听

// 派发自定义事件
node.event("custom-event", [data1, data2]);
node.on("custom-event", this, (d1, d2) => { });

// Laya.Event 常用常量
// CLICK, MOUSE_DOWN, MOUSE_UP, MOUSE_MOVE, MOUSE_OVER, MOUSE_OUT
// TOUCH_BEGIN, TOUCH_MOVE, TOUCH_END
// CHANGE, COMPLETE, PROGRESS, ERROR
// RESIZE, BLUR, FOCUS

Resource loading

// 批量加载
const assets = [
    { url: "res/img/hero.png", type: Laya.Loader.IMAGE },
    { url: "res/atlas/ui.atlas", type: Laya.Loader.ATLAS },
    { url: "res/config/data.json", type: Laya.Loader.JSON },
];
Laya.loader.load(assets, Laya.Handler.create(this, this.onLoaded),
    Laya.Handler.create(this, this.onProgress));

private onLoaded(): void {
    // 获取缓存资源
    const tex = Laya.loader.getRes("res/img/hero.png") as Laya.Texture;
}

private onProgress(progress: number): void {
    console.log(`加载进度: ${Math.floor(progress * 100)}%`);
}

// 单个加载
Laya.loader.load("res/scene/game.json", Laya.Handler.create(this, (res) => {
    Laya.stage.addChild(Laya.loader.getRes("res/scene/game.json") as Laya.Sprite);
}));

// 释放资源
Laya.loader.clearRes("res/img/hero.png");
Laya.loader.clearTextureRes("res/img/hero.png");

Handler (callback wrapper)

// 创建一次性 Handler(执行后自动销毁)
const handler = Laya.Handler.create(caller, callback, args, true);

// 创建持久 Handler(不自动销毁)
const handler = Laya.Handler.create(caller, callback, args, false);

// 手动回收
handler.recover();

Tween easing

// 基础缓动
Laya.Tween.to(sprite, { x: 500, y: 300, alpha: 1 }, 1000, Laya.Ease.sineOut,
    Laya.Handler.create(this, this.onComplete));

// 从某状态缓动至当前
Laya.Tween.from(sprite, { x: 0, y: 0 }, 500, Laya.Ease.backOut);

// 停止缓动
Laya.Tween.clearAll(sprite);       // 清除该目标所有缓动
Laya.Tween.clear(tweenInstance);   // 清除指定缓动实例

Timer timers

// 循环执行(毫秒)
Laya.timer.loop(1000, this, this.onTick);

// 延迟一次
Laya.timer.once(2000, this, this.onDelayed);

// 每帧执行
Laya.timer.frameLoop(1, this, this.onFrameTick);

// 清理
Laya.timer.clear(this, this.onTick);    // 清除特定定时器
Laya.timer.clearAll(this);              // 清除当前对象所有定时器

UI system (IDE-generated)

// 加载并显示 UI 场景
class GameUI extends ui.GameUIUI {
    constructor() {
        super();
        // IDE 生成的属性已绑定,直接使用
        this.btnStart.on(Laya.Event.CLICK, this, this.onBtnStart);
        this.lblScore.text = "0";
    }

    private onBtnStart(): void {
        // 处理按钮事件
    }
}

Key differences between 2.0 and 1.0

Feature 2.0 (this skill) 1.0
Script components Inherits Laya.Script, full lifecycle No component system, uses regular TypeScript classes
IDE property injection @prop {name,type} annotation injection Not supported
Scene management IDE scene editor + Laya.Scene.open() No scene management
Physics engine Built-in Box2D None built-in (requires manual integration)
3D Built-in 3D support 3D as a separate module
Skeletal animation Laya.Skeleton laya.ani.bone.Skeleton

Suggested directory structure

src/
├── Main.ts              # 入口文件
├── gameConfig.ts        # 全局配置
├── manager/             # 单例管理器
│   ├── GameManager.ts
│   ├── AudioManager.ts
│   └── DataManager.ts
├── scene/               # 场景(对应 IDE 场景文件)
│   ├── GameScene.ts
│   └── UIScene.ts
├── script/              # Script 组件脚本
│   ├── PlayerScript.ts
│   └── EnemyScript.ts
├── common/              # 公共工具
│   ├── ObjectPool.ts
│   └── EventBus.ts
└── ui/                  # IDE 生成的 UI 基类(勿手动修改)
    └── GameUIUI.ts