前面4篇下来,游戏基本上已经可以玩了。笔者想了想但还有两个问题,给大伙补上吧。1:颜色块移动速度一成不变;2:没有声音。那么下面来看看增加移动速度的代码,在game.js脚本里面增加函数:
startTimmer:function()
{
if(this.m_moveTime>1) //移动时间大于1秒时
{
this.m_moveTime-=0.5 //减少0.5秒移动时间,相当于提速
}
else
{
this.unschedule(this.startTimmer)
}
},
在game.js中开启定时器:
onLoad () {
this.gameWinDow=this.node.getContentSize()
this.oriPlayerPos=this.m_player.getPosition()
this.orignPos2=this.m_bg2.getPosition()
this.orignPos1=this.m_bg1.getPosition()
this.gameStart()
this.jsOperator=this.node.getParent().getChildByName("operator").getComponent("operation")
//设置随机种子
Math.seed = 5;
Math.seededRandom = function(max, min) {
max = max || 1;
min = min || 0;
Math.seed = (Math.seed * 9301 + 49297) % 233280;
var rnd = Math.seed / 233280.0;
return min + rnd * (max - min);
};
this.schedule(this.startTimmer,5) //开启定时器,5秒加速一次
},
因为m_moveTime在创建颜色块的时候,会传递给颜色块,作为颜色块的速度,于是提速目的达成:
//随机创建颜色块
createIceOrFire:function()
{
let randNum=(Math.seededRandom()*10).toFixed(0)
let type=randNum%2
let item=null
if(type==0)
{
item=cc.instantiate(this.m_icePre)
}
else
{
item=cc.instantiate(this.m_firePre)
}
this.node.addChild(item,10)
let randY=(randNum%5+1)*(this.gameWinDow.height/18)+184
let oriPos=cc.p(this.gameWinDow.width+item.getContentSize().width/2,randY)
let randY2=(randNum%5+1)*(this.gameWinDow.height/18)+184
let movePos=cc.p(-this.gameWinDow.width,randY2)
item.getComponent("ice").init(oriPos,movePos,this.m_player,this.m_moveTime)//这里用到了m_moveTime
item.getComponent("ice").m_game=this
},
然后增加游戏声音吧。在game.js里的onload函数中播放背景音乐:
onLoad () {
soundMgr.playGameBgMusic() //播放背景音乐
//此处省略了很多代码
},
下面来看看soundMgr.js脚本:
//声音管理类
var soundObj={
volume:0,
affectVolume:0,
init:function(){
this.urlBegan="res/raw-assets/resources/sound/"
this.volume=1 //音乐音量
this.affectVolume=1 //音效音量
},
//播放游戏背景音乐
playGameBgMusic:function(){
this.currBgMusic=cc.audioEngine.play(this.urlBegan+"Leshphon.mp3", true,this.volume); //true表示循环播放
},
}
soundObj.init()
module.exports=soundObj //这样才能被外部requere调用
在game.js脚本里面引用声音脚本:
var soundMgr=require("soundMgr")
cc.Class({
extends: cc.Component,
//此处省略了很多代码
}
其他声音以此类推。下面附上笔者的工程节点目录和资源目录结构:
好了,小游戏到此告一段落,没想到做小游戏就2天,写博客也要2天~