import SKDataUtil from "../util/SKDataUtil"; import SKUIUtil from "../util/SKUIUtil"; // 動畫控制 export default class SKAnimation { static debug: boolean = false; static playAni(node: cc.Node, url: string, speed: number = 12) { if (!node) { cc.log("必須有結點才能播放動畫", url); console.log("必須有結點才能播放動畫", url) return; } if (SKDataUtil.isEmptyString(url)) { let sprite = node.getComponent(cc.Sprite); if (sprite) { sprite.spriteFrame = null; } let ani = node.getComponent(cc.Animation); if (ani) { ani.stop(); } return; } let atlas = cc.loader.getRes(url, cc.SpriteAtlas); if (atlas) { this.playOfAtlas(node, atlas, url, speed); if (this.debug) { cc.log("從加載圖集緩存中播放動畫", url); console.log("從加載圖集緩存中播放動畫", url) } return; } cc.loader.loadRes(url, cc.SpriteAtlas, (error, result: cc.SpriteAtlas) => { if (error) { cc.warn("加載動畫資源錯誤", url, error.message); console.log("加載動畫資源錯誤", url, error.message) return; } SKAnimation.playOfAtlas(node, result, url, speed); }); } // 通過紋理圖集播放動畫 static playOfAtlas(node: cc.Node, atlas: cc.SpriteAtlas, url: string, speed: number = 12) { if (!SKUIUtil.isValid(node)) { cc.log("node is invalid......") return; } let frames = atlas.getSpriteFrames(); let clip = cc.AnimationClip.createWithSpriteFrames(frames, speed); clip.name = url; clip.wrapMode = cc.WrapMode.Loop; let sprite = node.getComponent(cc.Sprite); if (!sprite) { sprite = node.addComponent(cc.Sprite); } sprite.spriteFrame = frames[0]; sprite.sizeMode = cc.Sprite.SizeMode.RAW; sprite.trim = false; let ani = node.getComponent(cc.Animation); if (!ani) { ani = node.addComponent(cc.Animation); } let index = ani.getClips().indexOf(clip); if (index == -1) { ani.addClip(clip); } ani.play(clip.name); if (this.debug) { cc.log("播放動畫:", url); } } }