Unity2Dで「マッチ3のパズルゲームを作成」Part3です。
はじめに
前回の続きのPart3を作成していきます。Part2は下記から。
前回まで「ピースの生成・ボードの作成」、「ピースの入れ替え」を作成しました。Part3では「ピースの削除」を行っていきます。
ゲーム作成開始
ピースをスライドして、同じ色が3つ以上並んだ場合、ピースを削除していきます。
並んでいるピースをカウント
「Board」スクリプトのUpdate内に「Check」を追加します。Check内では左下から右方向に同じ色のピースが何個連続して並んでいるかをチェック、ピースを保持しています。
private void Update()
{
//略
if (isSlide)
{
PieceSlide();
Check();
}
}
private void Check()
{
List<Vector3Int> pieceList = new List<Vector3Int>();
Vector3Int pos = new Vector3Int(0, 0, 0);
ColorType color = dic[pos].colorType;
for (int i = 0; i < width; i++)
{
if (dic.TryGetValue(pos, out Piece piece) && piece.colorType == color)
{
pieceList.Add(pos);
pos += Vector3Int.right;
}
else
{
break;
}
}
Debug.Log(pieceList.Count);
}
実行してピースを移動してカウントが正しく出来ればOKです。

ピースを削除
Check関数を下記の様に変更します。パラメータでポイント、方向、数を指定します。指定したポイントから指定した方向へ指定した数だけループ。同じ色のピースが3つ以上の場合、リストに格納してパラメータで返します。
private void Check(Vector3Int pos, Vector3Int direction, int count, List<Vector3Int> delList)
{
List<Vector3Int> pieceList = new List<Vector3Int>();
ColorType color = dic[pos].colorType;
for (int i = 0; i < count; i++)
{
if (dic.TryGetValue(pos, out Piece piece) && piece.colorType == color)
{
pieceList.Add(pos);
pos += direction;
}
else
{
break;
}
}
if (pieceList.Count >= 3)
{
for (int cnt = 0; cnt < pieceList.Count; cnt++)
{
if (!delList.Contains(pieceList[cnt]))
delList.Add(pieceList[cnt]);
}
}
}
Update内に「MatchCheck」を追加、MachCheckでは全てのピースに対し、右方向と上方向にCheckを呼び出し、最後に格納されたリストのピースを削除しています。
private void Update()
{
//略
if (isSlide)
{
PieceSlide();
MatchCheck();
}
}
private void MatchCheck()
{
List<Vector3Int> delList = new List<Vector3Int>();
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
Vector3Int pos = new Vector3Int(x, y, 0);
Check(pos, Vector3Int.right, width - x, delList);
Check(pos, Vector3Int.up, height - y, delList);
}
}
DeletePiece(delList);
}
private void DeletePiece(List<Vector3Int> delList)
{
foreach (var item in delList)
{
dic.TryGetValue(item, out Piece piece);
Destroy(piece.gameObject);
dic.Remove(item);
}
}
実行して、下記の様に3つ以上同じ色が並んだピースが削除されたらOKです。

