【Laya】Laya 类使用说明

Laya 类使用说明

概述

Laya 类是 LayaAir 引擎的全局对象引用入口集。它提供了对核心全局对象的访问,如舞台 (Laya.stage)、时间管理器 (Laya.timer)、资源加载器 (Laya.loader) 等。

重要Laya 类的所有成员都是静态的,使用时必须通过 Laya.xxx 访问,注意大小写。

全局对象引用

属性 类型 说明
Laya.stage Laya.Stage 舞台对象的引用,所有显示对象的根容器
Laya.timer Laya.Timer 游戏主时钟,支持时间缩放,用于动画、缓动等
Laya.systemTimer Laya.Timer 系统时钟,引擎内部使用,不受时间缩放影响
Laya.physicsTimer Laya.Timer 物理时钟,用于物理引擎模拟
Laya.loader Laya.Loader 资源加载管理器
Laya.physics2D Laya.IPhysics2DFactory 2D物理引擎工厂

三种 Timer 对比

Timer 用途 scale 影响 典型场景
Laya.timer 游戏主时钟 ✅ 受影响 游戏逻辑、动画、UI、缓动效果
Laya.systemTimer 系统时钟 ❌ 不受影响 倒计时、网络请求、引擎内部
Laya.physicsTimer 物理时钟 ❌ 不受影响 物理引擎模拟
typescript 复制代码
// 游戏逻辑 - 可通过 scale 实现快进/慢放
Laya.timer.scale = 0.5;  // 慢放:50%速度
Laya.timer.loop(1000, this, this.onGameUpdate);

// 倒计时 - 不受游戏时间缩放影响
Laya.systemTimer.loop(1000, this, this.onCountDown);

// 物理模拟 - 保持稳定,不受游戏变速影响
// 物理引擎内部自动使用 physicsTimer,通常无需手动调用

静态方法

引擎初始化

方法 说明
init(width: number, height: number): Promise<void> 使用指定宽高初始化引擎
init(stageConfig?: Laya.IStageConfig): Promise<void> 使用配置对象初始化引擎

初始化回调

方法 说明
`addBeforeInitCallback(callback: (stageConfig: Laya.IStageConfig) => void Promise<void>): void`
`addAfterInitCallback(callback: () => void Promise<void>): void`
`addInitCallback(callback: () => void Promise<void>): void`

错误处理

方法 说明
alertGlobalError(value: boolean): void 是否捕获全局错误并弹窗显示
`_onGlobalError(ev: ErrorEvent PromiseRejectionEvent): void`

其他

方法 说明
importNative(name: string): any 导入原生库(dll/so/dylib)

基本用法

1. 引擎初始化

typescript 复制代码
// 方式1: 使用宽高参数
Laya.init(1136, 640).then(() => {
    console.log("引擎初始化完成");
});

// 方式2: 使用配置对象
Laya.init({
    designWidth: 1136,      // 设计宽度(非width)
    designHeight: 640,      // 设计高度(非height)
    scaleMode: Laya.Stage.SCALE_FIXED_AUTO,
    alignV: Laya.Stage.ALIGN_MIDDLE,
    alignH: Laya.Stage.ALIGN_CENTER,
    backgroundColor: "#232628"
}).then(() => {
    console.log("引擎初始化完成");
});

2. 访问全局对象

typescript 复制代码
// 访问舞台
Laya.stage.addChild(sprite);
Laya.stage.bgColor = "#232628";

// 访问时间管理器
Laya.timer.loop(1000, this, this.onUpdate);
Laya.timer.scale = 0.5;  // 慢放效果

// 访问资源加载器
Laya.loader.load("res/image.png").then(() => {
    const texture = Laya.loader.getRes("res/image.png");
});

完整示例

示例1: 基础引擎初始化

typescript 复制代码
export class BasicInitExample {
    constructor() {
        this.initEngine();
    }

    private initEngine(): void {
        Laya.init(1136, 640).then(() => {
            this.setupStage();
            this.createContent();
        });
    }

    private setupStage(): void {
        Laya.stage.alignV = Laya.Stage.ALIGN_MIDDLE;
        Laya.stage.alignH = Laya.Stage.ALIGN_CENTER;
        Laya.stage.scaleMode = Laya.Stage.SCALE_SHOWALL;
        Laya.stage.bgColor = "#232628";
    }

    private createContent(): void {
        const sprite = new Laya.Sprite();
        sprite.graphics.drawRect(0, 0, 200, 100, "#FF5722");
        sprite.pos(Laya.stage.width / 2, Laya.stage.height / 2);
        sprite.pivot(100, 50);
        Laya.stage.addChild(sprite);
    }
}

示例2: 使用配置对象初始化

typescript 复制代码
export class ConfigInitExample {
    constructor() {
        this.initWithConfig();
    }

    private initWithConfig(): void {
        Laya.init({
            designWidth: 0,        // 0 表示全屏
            designHeight: 0,
            scaleMode: Laya.Stage.SCALE_FIXED_AUTO,
            screenMode: Laya.Stage.SCREEN_NONE,
            alignV: Laya.Stage.ALIGN_MIDDLE,
            alignH: Laya.Stage.ALIGN_CENTER,
            backgroundColor: "#232628"
        }).then(() => {
            Laya.Stat.show();  // 显示性能统计
            this.onReady();
        });
    }

    private onReady(): void {
        console.log("引擎已就绪");
        console.log("舞台尺寸:", Laya.stage.width, Laya.stage.height);
    }
}

示例3: 自定义初始化回调

typescript 复制代码
export class Main {
    constructor() {
        // 注册初始化前回调
        Laya.addBeforeInitCallback((stageConfig) => {
            console.log("初始化前,可修改配置");
            // 根据环境动态调整配置
            if (Laya.Browser.onMobile) {
                stageConfig.designWidth = 0;
                stageConfig.designHeight = 0;
            }
        });

        // 注册初始化后回调
        Laya.addAfterInitCallback(() => {
            console.log("初始化完成,引擎已就绪");
            this.onEngineReady();
        });

        // 开始初始化
        Laya.init(1136, 640);
    }

    private onEngineReady(): void {
        // 设置舞台属性
        Laya.stage.scaleMode = Laya.Stage.SCALE_FIXED_AUTO;
        Laya.stage.bgColor = "#232628";

        // 预加载资源
        this.preloadResources();
    }

    private preloadResources(): void {
        Laya.loader.load([
            "res/ui.atlas",
            "res/audio/bgm.mp3"
        ]).then(() => {
            console.log("资源加载完成");
        });
    }
}

示例4: 3D 引擎初始化

typescript 复制代码
export class Engine3DInitExample {
    constructor() {
        Laya.init(0, 0).then(() => {
            this.setup3DStage();
            this.create3DScene();
        });
    }

    private setup3DStage(): void {
        Laya.stage.scaleMode = Laya.Stage.SCALE_FULL;
        Laya.stage.screenMode = Laya.Stage.SCREEN_NONE;
    }

    private create3DScene(): void {
        // 创建3D场景
        const scene = new Laya.Scene3D();
        Laya.stage.addChild(scene);

        // 创建相机
        const camera = new Laya.Camera(0, 0.1, 100);
        camera.transform.translate(new Laya.Vector3(0, 1, -5));
        scene.addChild(camera);

        // 创建方向光
        const light = new Laya.Sprite3D();
        const lightCom = light.addComponent(Laya.DirectionLightCom);
        lightCom.color = new Laya.Color(1, 1, 1, 1);
        scene.addChild(light);
    }
}

示例5: 全局错误处理

typescript 复制代码
export class ErrorHandlingExample {
    constructor() {
        // 启用全局错误捕获
        Laya.alertGlobalError(true);

        Laya.init(1136, 640).then(() => {
            console.log("引擎初始化完成");
        });
    }
}

// 在 config.js 中设置全局错误处理(LayaNative 环境)
window.onLayaInitError = function(e: any) {
    console.log("引擎初始化失败:", e);
    alert("加载游戏失败,请检查网络后重试");
};

示例6: 多阶段初始化流程

typescript 复制代码
export class MultiStageInitExample {
    private stageConfig: Laya.IStageConfig;

    constructor() {
        this.stageConfig = {
            designWidth: 1136,
            designHeight: 640,
            scaleMode: Laya.Stage.SCALE_FIXED_AUTO
        };

        this.setupCallbacks();
    }

    private setupCallbacks(): void {
        // 阶段1: 初始化前 - 环境检测
        Laya.addBeforeInitCallback((config) => {
            this.detectEnvironment();
            this.applyPlatformSettings(config);
        });

        // 阶段2: 初始化后 - 引擎配置
        Laya.addAfterInitCallback(() => {
            this.configureStage();
        });

        // 阶段3: 自定义模块初始化
        Laya.addInitCallback(() => {
            return this.initPhysics();
        });

        Laya.addInitCallback(() => {
            return this.initAudio();
        });

        // 开始初始化
        Laya.init(this.stageConfig);
    }

    private detectEnvironment(): void {
        console.log("平台:", Laya.Browser.platform);
        console.log("移动端:", Laya.Browser.onMobile);
        console.log("微信小游戏:", Laya.Browser.onMiniGame);
    }

    private applyPlatformSettings(config: Laya.IStageConfig): void {
        if (Laya.Browser.onMobile) {
            config.designWidth = 0;
            config.designHeight = 0;
            config.scaleMode = Laya.Stage.SCALE_FIXED_AUTO;
        }
    }

    private configureStage(): void {
        Laya.stage.alignV = Laya.Stage.ALIGN_MIDDLE;
        Laya.stage.alignH = Laya.Stage.ALIGN_CENTER;
        Laya.stage.bgColor = "#232628";
    }

    private async initPhysics(): Promise<void> {
        console.log("初始化物理引擎");
        // 物理引擎初始化逻辑
    }

    private async initAudio(): Promise<void> {
        console.log("初始化音频系统");
        // 音频系统初始化逻辑
    }
}

示例7: 运行时动态配置

typescript 复制代码
export class RuntimeConfigExample {
    private isLandscape: boolean = false;

    constructor() {
        Laya.addBeforeInitCallback((config) => {
            // 根据屏幕方向动态配置
            this.isLandscape = window.innerWidth > window.innerHeight;

            if (this.isLandscape) {
                config.screenMode = Laya.Stage.SCREEN_HORIZONTAL;
            } else {
                config.screenMode = Laya.Stage.SCREEN_VERTICAL;
            }
        });

        Laya.init({
            designWidth: 0,
            designHeight: 0,
            scaleMode: Laya.Stage.SCALE_FIXED_AUTO
        }).then(() => {
            this.handleOrientationChange();
        });
    }

    private handleOrientationChange(): void {
        window.addEventListener("resize", () => {
            const nowLandscape = window.innerWidth > window.innerHeight;
            if (nowLandscape !== this.isLandscape) {
                this.isLandscape = nowLandscape;
                console.log("屏幕方向改变:", this.isLandscape ? "横屏" : "竖屏");
            }
        });
    }
}

注意事项

1. 回调执行顺序

typescript 复制代码
// 执行顺序:
// 1. addBeforeInitCallback 注册的回调(按注册顺序)
// 2. Laya.init() 执行引擎初始化
// 3. addInitCallback 注册的回调(并行执行)
// 4. addAfterInitCallback 注册的回调(按注册顺序)

Laya.addBeforeInitCallback(() => console.log("1"));
Laya.addBeforeInitCallback(() => console.log("2"));
Laya.addAfterInitCallback(() => console.log("4"));
Laya.addAfterInitCallback(() => console.log("5"));
Laya.addInitCallback(() => console.log("3"));

Laya.init().then(() => console.log("初始化完成"));
// 输出: 1, 2, 3, 初始化完成, 4, 5

2. 调试模式

typescript 复制代码
// 显示性能统计面板
Laya.Stat.show();

// 自定义位置
Laya.Stat.show(x, y);

// 启用WebGL调试
Laya.Shader3D.debugMode = true;
相关推荐
那个村的李富贵14 小时前
Unity自适应文本提示框:从原理到实战
unity·游戏引擎
WarPigs15 小时前
Unity人物翻越功能
unity·游戏引擎
游乐码15 小时前
Unity基础(四)向量相关
游戏·unity·游戏引擎
濮水大叔16 小时前
告别 Django Admin!这个 NodeJS 全栈框架让你在 DTO 中直接配置 Table/Form 渲染
前端·typescript·node.js
VT LI17 小时前
Cocos2d-x 引擎架构全面深度解析:从底层渲染到上层交互的系统性技术全景
游戏引擎·cocos·引擎架构
Kurisu57517 小时前
探灵直播2026最新官方正版免费下载 一键转存 永久更新 (看到速转存 资源随时走丢)
游戏·游戏引擎·游戏程序·动画·关卡设计
神码编程18 小时前
【Unity】MiniGame编辑器小游戏(十五)中国象棋局域网对战【Chinese Chess】(上)
unity·编辑器·游戏引擎·小游戏
伽蓝_游戏18 小时前
第四章:AssetBundle 核心机制与文件结构
unity·c#·游戏引擎·游戏程序
前端若水18 小时前
技术选型:React 19 + TypeScript + TailwindCSS
前端·react.js·typescript