开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第5天,点击查看活动详情
回顾下我们上次所说的内容。上次我们简单说了一下如何显示顶部的水果元素,以及写了下个创建水果元素的函数,但还没说在什么时候调用该函数。今天我们说下什么时候调用该函数。
1. 是不是当我们移动顶部的水果元素,当松开手的时候,是不是应该让它重新生成一个一样的水果元素。让它做自由落体运动。当产生水果元素时,顶部的元素也要产生新的下一个,因此也要调用this.show_block()函数。调用前还要产生一个1到5的随机数。
onTouchEnd(event: EventTouch) {
this.block_show.active=false
let pos_blockShow=this.block_show.getPosition()
this.crateBlock(this.block_random,pos_blockShow,false)
this.block_random=Math.floor(Math.random()*5)+1 //1到5随机数
this.scheduleOnce(function() {
this.show_block()
}.bind(this), 2);
}
2. 当水果元素做自由落体运动后,就会与地面上的水果发生碰撞。因此要做一些碰撞的处理。在脚本block.ts上进行处理。主要用到函数了碰撞回调函数。碰撞体回调需要在开始的时候进行注册,因此要在start()函数上加上以下代码
let collider = this.getComponent(Collider2D);
if (collider) {
collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
collider.on(Contact2DType.END_CONTACT, this.onEndContact, this);
collider.on(Contact2DType.PRE_SOLVE, this.onPreSolve, this);
collider.on(Contact2DType.POST_SOLVE, this.onPostSolve, this);
}
3. 在碰撞函数进行处理。当相同的水果产生碰撞后就需要生成更大的水果,因此需要调用生成新的水果函 this.tsGame.crateBlock(this.block_type+1,this.pos,true) 并且要大一级的,所以block_type要加1。
onBeginContact (selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
// 只在两个碰撞体开始接触时被调用一次
if(otherCollider.tag !=11){
this.is_pz=true
}
let js_otherBlock=otherCollider.getComponent(block)
if(js_otherBlock && this.can_pz){
if(this.block_type==js_otherBlock.block_type){
this.can_pz=false
js_otherBlock.can_pz=false
let pos_self= selfCollider.node.getPosition()
let pos_other= otherCollider.node.getPosition()
this.pos=pos_self
if(this.pos.y >pos_other.y){
this.pos=pos_other
}
setTimeout(function () {
this.tsGame.crateBlock(this.block_type+1,this.pos,true)
let block_wh=this.node.width
}.bind(this), 100);
tween(selfCollider.node)
.delay(0.05)
.removeSelf()
.start()
tween(otherCollider.node)
.delay(0.05)
.removeSelf()
.start()
}
}
}
今天就到这里了,主要说了产生碰撞后的一些处理,我们下次再说。可能写的过程中还有很多不好的地方,希望大家能指出来,在此,谢谢大家