PVZ系列四 | 子弹

首先我们要搞清楚攻击的逻辑。
植物检测到前方有僵尸,然后生成一个子弹。
子弹每一帧前进,如果检测碰撞到僵尸就消失。
消失的同时,僵尸扣血。

效果预览

在这里插入图片描述

首先,要让子弹生成

在这里插入图片描述

function onEnterFrm(){
	//
	// 植物管理
	//
	for (i = 0; i < plantContainer.numChildren; i++) {
		var currentPlant = plantContainer.getChildAt(i);//遍历每个植物
		// 准备好开火
		if (currentPlant.recharge == currentPlant.fireRate ) {
			// 检查是否有僵尸与植物处于同一行
			if (zombiesArray[currentPlant.plantRow].length > 0) {
				// 同行有僵尸
				for (j=0; j < zombiesArray[currentPlant.plantRow].length; j++) {//遍历当前行的僵尸
					var targetZombie = zombieContainer.getChildByName(zombiesArray[currentPlant.plantRow][j]);// 获取僵尸
					// 僵尸在右
					if (targetZombie.x > currentPlant.x) {
						var bullet = new lib.bulletMc();// 构造新子弹
						bulletContainer.addChild(bullet);// 添加子弹
						bullet.x = currentPlant.x+20;
						bullet.y = currentPlant.y;
						bullet.sonOf = currentPlant;//子弹当儿子,存储该子弹是由哪一株植物射出的
						currentPlant.recharge = 0;// 重新装填
						break;// exits the j for loop
					}
				}
			}
		}
		// 子弹装填中
		if (currentPlant.recharge < currentPlant.fireRate) {
			currentPlant.recharge ++;// recharges the plant
		}
	}
}

这样,当我们的植物检测到自己这行右边有僵尸后,就会生成一个子弹。
这个子弹会被存入bulletContainer中。

让子弹动起来打僵尸

在这里插入图片描述

function onEnterFrm(){
	//
	// 子弹管理
	//
	for (i=0; i<bulletContainer.numChildren; i++) {
		var movingBullet = bulletContainer.getChildAt(i);
		movingBullet.x+=3;//子弹移动
		var firingPlant = movingBullet.sonOf;//获得这个子弹是哪个植物射击的
		// 子弹飞走了
		
		for (j=0; j<zombieContainer.numChildren; j++) {
			var movingZombie=zombieContainer.getChildAt(j);
			if (movingZombie.zombieRow != firingPlant.plantRow) continue;
			// 碰撞检测
			if (movingZombie.x < movingBullet.x && movingZombie.x > movingBullet.x-5 ){
				movingZombie.alpha-=0.3;// 僵尸逐渐死亡
				bulletContainer.removeChild(movingBullet);// 移除子弹
				// 僵尸死了
				if (movingZombie.alpha<0) {
					zombiesArray[movingZombie.zombieRow].splice(zombiesArray[movingZombie.zombieRow].indexOf(movingZombie.name),1);// 减少该行的僵尸 
					zombieContainer.removeChild(movingZombie);// 移除显示列表
				}
				break;
			}
		}
		if (movingBullet.x>1200) {
			bulletContainer.removeChild(movingBullet);// 移除这颗子弹
		}
	}
}

这里面最重要的就是搞清楚二重循环的逻辑。

总结

现在,我们基本的游戏规则已经出来啦。
后面就要在这个框架上进行更多的润色。

发布了14 篇原创文章 · 获赞 26 · 访问量 3302

猜你喜欢

转载自blog.csdn.net/weixin_44338553/article/details/103188893