跨場景訪問節點
我們來看一下之前做的菜單場景
中間有一個記錄的label我們一直沒理她,
今天我們就來翻她的牌子
我們每次遊戲結束時都會有一個分數,這個分數變量在相應的遊戲場景裏,我們想要的效果時:當返回菜單時,我們要把這個分數變量帶回來,但當場景銷燬時,其中的所有節點都會隨之消失
這裏就要引出另一個重要的知識點,同學們拿筆記一下
沒帶筆的前後桌借一下
不會跟隨場景銷燬的節點——常駐節點
我們回到第一個Load場景,添加一個根節點(必須是根節點哦)Record
Record.js
cc.Class({
extends: cc.Component,
properties: {
bestRunScore: 0,
bestJumpScore: 0,
},
onLoad: function () {
cc.game.addPersistRootNode(this.node);
var bestRunScore = cc.sys.localStorage.getItem("bestRunScore");
if(bestRunScore){
this.bestRunScore = bestRunScore;
}
var bestJumpScore = cc.sys.localStorage.getItem("bestJumpScore");
if(bestRunScore){
this.bestJumpScore = bestJumpScore;
}
},
updateRunScore: function(score){
if(score > this.bestRunScore){
this.bestRunScore = score;
}
},
updateJumpScore: function(score){
if(score > this.bestJumpScore){
this.bestJumpScore = score;
}
},
save(){
cc.sys.localStorage.setItem('bestRunScore', this.bestRunScore);
cc.sys.localStorage.setItem('bestJumpScore', this.bestJumpScore);
},
});
我們在onLoad方法裏將Record節點變成遊戲的常駐節點
cc.game.addPersistRootNode(this.node);
銷燬的方法是
cc.game.removePersistRootNode(node);
遊戲中的常駐節點,在切換場景時不會銷燬,所以我們可以把一些需要跨場景訪問的方法和變量添加到常駐節點的腳本里
我們切換到Menu場景
寶強同學驚奇的發現,那個常駐節點Record並沒有出現!
寶強同學就是太實在
有些事情光靠眼睛是發現不了的
常駐節點只是邏輯上的,並不會在其他場景層級管理器裏出現
“層級管理器裏都沒有,那怎麼用啊”
這就要用另一個找節點的方法了
cc.find();
我們修改兩個Game的stopGame方法
Game.js
stopGame: function(){
cc.director.getCollisionManager().enabled = false;
this.gameOverMenu.active = true;
this.overScore.string = this.score+"m";
//存儲數據
cc.find("Record").getComponent("Record").updateRunScore(this.score);
},
Game2.js
stopGame: function(){
cc.director.getCollisionManager().enabled = false;
this.gameOverMenu.getChildByName('OverScore').getComponent(cc.Label).string = this.score;
this.gameOverMenu.active = true;
//存儲數據
cc.find("Record").getComponent("Record").updateJumpScore(this.score);
},
存儲與讀取數據
存儲數據
cc.sys.localStorage.setItem('bestRunScore', this.bestRunScore);
cc.sys.localStorage.setItem('bestJumpScore', this.bestJumpScore);
讀取數據
cc.sys.localStorage.getItem("bestRunScore");
cc.sys.localStorage.getItem("bestJumpScore");
就是兩個封裝的方法,存儲的方式是鍵值對
Menu腳本也需要修改一下
Menu.js
...
onLoad: function () {
this.record = cc.find("Record").getComponent("Record");
this.runScore.string = "你最遠跑了" + this.record.bestRunScore+ "m";
this.jumpScore.string = "你最高跳了" + this.record.bestJumpScore+ "m";
...
},
...
播放聲音
播放聲音有兩種方式
1.組件AudioSource
play ( )
播放音頻剪輯。
stop ( )
停止當前音頻剪輯。
pause ( )
暫停當前音頻剪輯。
resume ( )
恢復播放。
rewind ( )
從頭開始播放。
2.聲音系統
cc.audioEngine.playMusic(source);
cc.audioEngine.stopMusic(source);
cc.audioEngine.playEffect(source);
cc.audioEngine.stopEffect(source);
上面的第一種方法原生平臺有很多Bug,所以我們的遊戲都用的第二種方法播放聲音
打包發佈(修改圖標)
我們打包一個Android的Apk
模板選擇binary可以快速打包,Portrait豎屏,Upside Down倒屏,Landscape Left左右橫屏,Landscape Right右左橫屏
我們先點擊構建
構建完成後我們找到構建的目錄(就是上面的build文件夾)
build/jsb-binary/frameworks/runtime-src/proj.android/res/
將裏面的圖標換成我們的女主角
替換完成後再點擊編譯
進入下面的目錄就可以看見我們的Apk文件了