PVZ系列五 | 铲子

如果前面的逻辑都搞懂了,写铲子就十分的容易。
他跟种豌豆一模一样。

预览

在这里插入图片描述

逻辑

在这里插入图片描述

代码

记得定义一个全局变量isShoveling,他的作用和我们之间讲的isPlanting一样。

//
//铲子
//
function addShovel(){
	var card_shovel = new lib.shovelCard();
	overlayContainer.addChild(card_shovel);
	card_shovel.buttonMode = true;
	card_shovel.x = 250;
	card_shovel.y = 20;
	card_shovel.addEventListener("click", onShovelClicked);
}
function onShovelClicked(){
	shovelSelector = new lib.shovelMc();
	shovelSelector.alpha = 0.5;
	shovelSelector.visible = false;
	overlayContainer.addChild(shovelSelector);
	movingShovel = new lib.shovelMc();
	movingShovel.addEventListener("click", removePlant);
	overlayContainer.addChild(movingShovel);
	isShoveling = true;
}
function removePlant(){
	var plantRow = Math.floor((trueMouseY - borderTop) / gridHeight);
	var plantCol = Math.floor((trueMouseX - borderLeft) / gridWidth);
	movingShovel.removeEventListener("click", removePlant); // removes the CLICK listener from the draggable plant
	overlayContainer.removeChild(shovelSelector); // removes the selector
	overlayContainer.removeChild(movingShovel); // removes the plant itself
	// 判断鼠标是否在放置区域内部并且上面没有植物
	if (plantRow >= 0 && plantCol >= 0 && plantRow < 5 && plantCol < 9 && plantsArray[plantRow][plantCol] == 1) 
	{
		plantsArray[plantRow][plantCol] = 0; // 更新游戏区块信息
		var attackedPlant = plantContainer.getChildByName("plant_" + plantRow + "_" + plantCol);
		plantContainer.removeChild(attackedPlant); //removes the plant Display Object from Display List
	}
	playerMoving = false; // tells the script the player is no longer moving
}
function onEnterFrm() {
	//
	//铲子管理
	//
	if(isShoveling){
		movingShovel.x = trueMouseX;
		movingShovel.y = trueMouseY;
		var plantRow = Math.floor((trueMouseY - borderTop) / gridHeight);
		var plantCol = Math.floor((trueMouseX - borderLeft) / gridWidth);
		// 鼠标在区域内
		if (plantRow >= 0 && plantCol >= 0 && plantRow < 5 && plantCol < 9 && plantsArray[plantRow][plantCol] == 1) {
			shovelSelector.visible = true; // shows the selector
			shovelSelector.x = borderLeft + plantCol * gridWidth + 30;
			shovelSelector.y = borderTop + plantRow * gridHeight + 30;
		} else {
			shovelSelector.visible = false; // hide the selector
		}
	}
}

最后,记得在main()函数中把addShovel()加进去。

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

猜你喜欢

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