以向上移动为例
#region ToTop
for (int x = 0; x < 4; x++)
{
int emptyCount = 0;
Num preNum = null;
for (int y = 0; y < 4; y++)
{
if (NumIndexArray[x][y] == 0)
{
emptyCount++;
}
else
{
//初始Num
if (preNum == null) {
preNum = NumAssemblyArray[x][y];
//当查找到有数字的数组位置时,将其Num赋值给preNum
}
//合并
//当初是preNum有值且和下一个Num相同时,进行合并
else if (NumAssemblyArray[x][y].NumIndex == preNum.NumIndex)
{
//每有一个空位置,便增加1,用来计算移动的位置
emptyCount++;
//启动删除标记
//合并后需要将原来的两个Num删除
NumAssemblyArray[x][y].isDestory = true;
preNum.isDestory = true;
//将响应表格中的引用清除
preNum = null;
//延时并创建一个num
//CreateNum(x + emptyCount, y, NumAssemblyArray[x][y].NumIndex * 2);
//延时创建,保证原来的已经被删掉了
StartCoroutine(WaitAndCreateNum(x, y - emptyCount, NumAssemblyArray[x][y].NumIndex * 2, NumAssemblyArray[x][y].moveTime));
}
else
{
preNum = NumAssemblyArray[x][y];
}
//移动
int newX = NumAssemblyArray[x][y].InitX;
int newY = NumAssemblyArray[x][y].InitY - emptyCount;
NumAssemblyArray[x][y].UpdatePos(newX,newY);
if (newX != x || newY != y)
{
//确定移动后的新位置,无论是否有合并都会运行
NumAssemblyArray[newX][newY] = NumAssemblyArray[x][y];
NumIndexArray[newX][newY] = NumIndexArray[x][y];
//将原位置的Num删除,即使还没有移动结束,先删除。
NumAssemblyArray[x][y] = null;
NumIndexArray[x][y] = 0;
}
}
}
}
//在指定的一侧创建一个新的Num
CreateNum(TouchDir.Top);
#endregion
根据不同的情况,选择一个空的位置
#region moveToTop
int emptyNumCount = 0;
int y = 3;
for (int x = 0; x < 4; x++)
{
if (NumIndexArray[x][y] == 0)
{
emptyNumCount++;
}
}
if (emptyNumCount != 0)
{
int randomIndex = Random.Range(1, emptyNumCount + 1);
int count = 0;
for (int x = 0; x < 4; x++)
{
if (NumIndexArray[x][y] == 0)
{
count++;
if (count == randomIndex)
{
newX = x;
newY = y;
}
}
}
}
#endregion
等待并生成新的Num
通过携程实现
通过StartCoroutine(对象)方法启动。
#region 等待并且在合并时生成新的Num-WaitAndCreateNum(int x,int y,int index,float WaitTime)
IEnumerator WaitAndCreateNum(int x,int y,int index,float WaitTime) {
WaitTime -= 0.2f;
yield return new WaitForSeconds(WaitTime);
CreateNum(x, y, index);
}
#endregion
[下载源码](http://download.csdn.net/detail/tianyao9hen/9870850)