游戏开发实战之《冰火世界》(三)
上一篇讲到主角的切换状态和跳跃,现在颜色块也该出场了。笔者创建了一个单色精灵fire(懒得上网找图啊):
颜色设为红色,这样“火块”好名副其实。创建ice.js脚本:
cc.Class({
extends: cc.Component,
properties: {
m_player:null, //玩家
type:0, //类型,用来区分火块还是冰块
moveTime:0, //自身移动速度
m_game:null,
},
init:function(oriPos,movePos,player,movetime) //初始位置,移动位置,玩家,移动时间
{
this.m_player=player
if(typeof movetime=="number"&&movetime>0)
{
this.moveTime=movetime
}
this.node.setPosition(oriPos)
let call=cc.callFunc(function(){
this.node.removeFromParent()
}.bind(this))
this.node.runAction(cc.sequence(cc.moveTo(this.moveTime,movePos),call))
},
}
init函数传进参数设置颜色块起始位置、移动的终点位置、玩家引用(之后碰撞会用到)、颜色块移动时间。
把ice.js脚本挂到fire节点上:
然后,把fire节点从场景拖拽到资源目录,成为prefab(预制)。
冰颜色块预制也如法炮制:
好了,颜色块的预制都做好了。下面创建game.js脚本,用来控制游戏,比如:让颜色块出现在哪里。
cc.Class({
extends: cc.Component,
properties: {
m_bg1:{ //背景
default:null,
type:cc.Node
},
m_bg2:{
default:null,
type:cc.Node
},
m_icePre:{ //冰块
default:null,
type:cc.Prefab
},
m_firePre:{ //火块
default:null,
type:cc.Prefab
},
m_player:{ //玩家
default:null,
type:cc.Node
},
m_mapSpeed:0, //背景移动速度
m_bGameOver:false, //游戏是否结束
m_moveTime:0, //颜色块移动速度
},
//随机创建颜色块
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)
item.getComponent("ice").m_game=this
},
// LIFE-CYCLE CALLBACKS:
//游戏开始时,循环背景图
gameStart:function()
{
this.m_bg1.setPosition(this.orignPos1)
this.m_bg2.setPosition(this.orignPos2)
let moveBy1=cc.moveBy(this.m_mapSpeed,cc.p(-this.m_bg1.getContentSize().width,0))
let call1=cc.callFunc(function(){
this.m_bg1.setPosition(this.orignPos1)
}.bind(this))
let repeat1=cc.repeatForever(cc.sequence(moveBy1,call1))
this.m_bg1.runAction(repeat1)
let moveBy2=cc.moveBy(this.m_mapSpeed,cc.p(-this.m_bg2.getContentSize().width,0))
let call2=cc.callFunc(function(){
this.m_bg2.setPosition(this.orignPos2)
}.bind(this))
let repeat2=cc.repeatForever(cc.sequence(moveBy2,call2))
this.m_bg2.runAction(repeat2)
this.schedule(this.createIceOrFire,0.7) //每0.7秒创建一个颜色块
},
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);
};
},
}
现在挂一下脚本需要用到的节点和预制:
运行起来,应该可以看到颜色块0.7秒就会出现一个,位置是随机的。