LayaAir小牛
@23876:const { regClass, property } = Laya;
@regClass()
export default class iceMonster extends Laya.Script {
declare owner: Laya.Sprite;
/** 用于兜底的 Animator2D(可选) */
private _animator: Laya.Animator2D;
/** 承载 .mc 的动画播放器 */
private iceMonsterAni: Laya.Animation;
/** 资源前缀 */
private readonly ANIMATION_PATH: string = "resources/builtIngame3role/roleMonster/mc/";
/** 已加载的 .mc 资源路径数组 */
private loadedClips: string[] = [];
onEnable(): void {
this._animator = this.owner.getComponent<Laya.Animator2D>(Laya.Animator2D);
// 1. 创建 Laya.Animation 并挂到角色节点
this.iceMonsterAni = new Laya.Animation();
this.owner.addChild(this.iceMonsterAni);
this.iceMonsterAni.visible = false; // 默认隐藏
// 2. 开始加载
this.loadMcClips();
}
/* -------------------------------------------------
* 对外唯一接口:随机播一条
* ------------------------------------------------- */
public playRandomMove(): void {
if (this.loadedClips.length > 0) {
const clipPath = this.loadedClips[Math.floor(Math.random() * this.loadedClips.length)];
this.playMcClip(clipPath);
} else {
// 兜底:用 Animator2D 状态机
const idx = Math.floor(Math.random() * 8) + 1;
this._animator?.play(`move${idx}`);
}
}
/* -------------------------------------------------
* 加载 8 个 .mc 文件
* ------------------------------------------------- */
private loadMcClips(): void {
const urls: string[] = [];
for (let i = 1; i <= 8; i++) urls.push(`${this.ANIMATION_PATH}move${i}.mc`);
Laya.loader.load(urls, Laya.Handler.create(this, () => {
for (let i = 1; i <= 8; i++) {
const clipPath = `${this.ANIMATION_PATH}move${i}.mc`;
// 检查资源是否存在
if (Laya.loader.getRes(clipPath)) {
this.loadedClips.push(clipPath);
}
}
console.log(`[iceMonster] 成功加载 ${this.loadedClips.length} 个 .mc 剪辑`);
}));
}
/* -------------------------------------------------
* 播放指定剪辑
* ------------------------------------------------- */
private playMcClip(clipPath: string): void {
this.iceMonsterAni.visible = true;
this.iceMonsterAni.play(0, false, clipPath); // 0=起始帧 false=不循环 clipPath=动画资源路径
this.iceMonsterAni.once(Laya.Event.COMPLETE, this, () => {
this.iceMonsterAni.visible = false;
});
}
}
你看看。