cocos creator動態新增自定義元件
阿新 • • 發佈:2019-01-12
/** * 面板動畫陣列 */ var cow_skin = cc.Class({ name: "cow_skin", properties: { cow_anim: { type: cc.SpriteFrame, default:[], }, } }); // cc.Class({ extends: cc.Component, properties: { cow_skin_set: { default:[], type: cow_skin, }, }, // LIFE-CYCLE CALLBACKS: onLoad: function() { // game_scene元件 this.game_scene = cc.find("Canvas").getComponent("game_scene"); // 主動以程式碼形式為節點新增一個自定義元件 this.anim_com = this.node.addComponent("frame_anim"); this.cow_type = Math.floor(Math.random() * 3 + 1); //1-4 但是隻能取到3,做下越界處理 if(this.cow_type >= 4){ this.cow_type = 1; } this.speed_x = -(Math.random() * 100 + 100); this._play_cow_walk(); }, _play_cow_walk: function(){ this.anim_com.sprite_frames = this.cow_skin_set[this.cow_type - 1].cow_anim; this.anim_com.duration = 0.2; this.anim_com.play_loop(); }, start () { }, update (dt) { var sx = this.speed_x * dt; this.node.x += sx; }, });
1)一次只有一個場景,所以可以從Canvas下面索引當前場景上的元件
this.game_scene = cc.find("Canvas").getComponent("game_scene");
2)可以動態給一個節點通過程式碼的形式給節點增加一個元件,而不用再編輯器中掛載的方式
this.anim_com = this.node.addComponent("frame_anim");