AS3游戏开发:子弹仅击中指定类型对象时更新分数的实现问题
实现方案
第一步:调整mcRandom类,增加类型标识
你的不同对象对应mcRandom时间轴的不同帧,我们新增一个公共属性存储当前对象的帧号作为类型区分标识,修改后的类代码如下:
package { import flash.display.MovieClip; import flash.events.Event; public class mcRandom extends MovieClip { public var sDirection:String; private var nSpeed:Number; // 新增:存储当前对象的类型ID,对应时间轴帧号 public var typeId:int; public function mcRandom() { addEventListener(Event.ADDED_TO_STAGE, onAdd); } private function onAdd(e:Event):void { removeEventListener(Event.ADDED_TO_STAGE, onAdd); init(); } private function init():void { // 你提到有4种对象,这里把原来的3改成4 var nRandomCells:Number = 4; var nRandom:Number = randomNumber(1, nRandomCells); // 给类型ID赋值 this.typeId = nRandom; this.gotoAndStop(nRandom); setupStartPosition(); } private function setupStartPosition():void { nSpeed = randomNumber(17, 22); var nLeftOrRight:Number = randomNumber(1, 2); if(nLeftOrRight == 1) { this.x = 0 - this.width / 2; sDirection = "R"; } else { this.x = stage.stageWidth + (this.width / 2); sDirection = "L"; } var nMinAltitude:Number = stage.stageHeight / 2; var nMaxAltitude:Number = this.height / 2; this.y = randomNumber(nMinAltitude, nMaxAltitude); startMoving(); } private function startMoving():void { addEventListener(Event.ENTER_FRAME, randomLoop); } private function randomLoop(e:Event):void { if(sDirection == "R") { this.x += nSpeed; } else { this.x -= nSpeed; } } function randomNumber(low:Number=0, high:Number=1):Number { return Math.floor(Math.random() * (1+high-low)) + low; } } }
第二步:修改碰撞检测逻辑,仅指定类型加分
在碰撞判定后,先判断击中对象的typeId是否为你要计分的目标类型,再执行计分逻辑即可,修改后的碰撞检测代码如下:
function checkBulletHitsRandom():void { for(var i:int = 0; i < bulletArray2.length; i++) { var currentBullet2:mcBullet = bulletArray2[i]; for(var j:int = 0; j < randomArray.length; j++) { var currentRandom:mcRandom = randomArray[j]; if(currentBullet2.hitTestObject(currentRandom)) { // 生成爆炸效果 var newExplosion2:mcExplosion = new mcExplosion(); stage.addChild(newExplosion2); newExplosion2.x = currentRandom.x; newExplosion2.y = currentRandom.y; // 移除子弹 currentBullet2.destroyBullet(); bulletArray2.splice(i, 1); // 移除被击中对象 currentRandom.destroyRandom(); randomArray.splice(j, 1); // 仅击中指定类型对象时才更新分数,比如你要帧2的对象加分,就判断typeId==2,自行修改数值即可 if(currentRandom.typeId == 2) { nScore2 += 2; updateScore2(); } // 数组splice后中断当前循环避免索引错误 break; } } } }
补充说明:如果你不需要击中非加分对象时产生爆炸、销毁子弹和对象,把爆炸、移除对象的相关逻辑也移到上面的if(currentRandom.typeId == 2)判断内部即可。
内容的提问来源于stack exchange,提问作者Mursyid Nasir
相关产品推荐
相关产品推荐

