U3D实战之CandyCrush

2015年02月02日 14:19 0 点赞 0 评论 更新于 2025-11-21 16:00

在Unity开发中,很多知识和经验都是在实际使用过程中逐步积累的。今天,我们将深入学习U3D实战项目——CandyCrush。

糖果属性面板与代码控制

首先,我们来看一种颜色的糖果属性面板(此处可自行补充对应图片)。以下是控制糖果生成的代码:

// 控制生成糖果的类型
private int candyTypeNumber = 7;
// 生成糖果材质素材
public GameObject[] BGs;
private GameObject bg;
// 指示糖果的颜色
public int type;
// 生成对GameController的引用
public GameController gameController;
private SpriteRenderer sr;

// 生成随机颜色的糖果
private void AddRandomBG()
{
// 如果糖果已有颜色,就不再生成
if (bg != null)
return;
// 随机生成一种颜色的糖果
type = Random.Range(0, Mathf.Min(candyTypeNumber, BGs.Length));
bg = (GameObject)Instantiate(BGs[type]);
sr = bg.GetComponent<SpriteRenderer>();
bg.transform.parent = this.transform;
}

需要注意的是,在确定可生成的糖果类型数量时,并非简单地取所有糖果类型的数量。因为如果类型过多,新生成的糖果可能无法与原有的糖果进行匹配消除,导致玩家后期无糖果可消。这个值需要根据实际情况来确定,在上述代码中,取值为 candyTypeNumber = 7

生成糖果时的匹配检查

在生成所有糖果时,我们需要检查是否在刚生成时就有糖果可以匹配消除。检查匹配情况分为同行检查和同列检查,以下是相关代码:

// 返回布尔值,显示是否能够交换
private bool CheckMatches()
{
return CheckHorizontalMatches() || CheckVerticalMatches();
}

由于这两种方法比较类似,我们仅介绍同一行(水平方向)的检查方法,垂直方向的检查与此类似:

// 检查水平方向是否有可以消除的
private bool CheckHorizontalMatches()
{
bool result = false;
for (int rowIndex = 0; rowIndex < rowNumber; rowIndex++)
{
for (int columnIndex = 0; columnIndex < columnNumber - 2; columnIndex++)
{
if ((GetCandy(rowIndex, columnIndex).type == GetCandy(rowIndex, columnIndex + 1).type) &&
(GetCandy(rowIndex, columnIndex + 1).type == GetCandy(rowIndex, columnIndex + 2).type))
{
// 播放匹配音效
audio.PlayOneShot(mathThreeClip);
result = true;
Debug.Log(columnIndex + " " + (columnIndex + 1) + " " + (columnIndex + 2));
AddMatches(GetCandy(rowIndex, columnIndex));
AddMatches(GetCandy(rowIndex, columnIndex + 1));
AddMatches(GetCandy(rowIndex, columnIndex + 2));
}
}
}
return result;
}

上述代码的主要功能是,对于每一行的糖果,检查是否有三个或三个以上的糖果类型相同。如果有,则将这些糖果添加到匹配数组中,以便统一处理同类型糖果的消除。

今天的内容就到这里。由于代码较多,表述可能有些杂乱,但只要理解了大致思路即可,毕竟实现该功能的方法并非唯一。感谢大家的阅读!

作者信息

feifeila

feifeila

共发布了 3994 篇文章