Bubble Shooter Game in Unity: Part 6

Finding matches in this grid is very similar to the logic I used in the match three game, particularly the “Tap to Match” variation.

Here’s the new logic in the Grid class:

public void CheckMatchesForBall (Ball ball) {

matchList.Clear ();

for (int row = 0; row < ROWS; row++) { for (int column = 0; column < COLUMNS; column++) { gridBalls [row] [column].visited = false; } } //search for matches around ball var initialResult = GetMatches( ball ); matchList.AddRange (initialResult); while (true) { var allVisited = true; for (var i = matchList.Count - 1; i >= 0 ; i--) {
var b = matchList [i];
if (!b.visited) {
AddMatches (GetMatches (b));
allVisited = false;
}
}

if (allVisited) {
if (matchList.Count > 2) {

foreach (var b in matchList) {
b.gameObject.SetActive (false);
}
}
return;
}
}
}

List GetMatches (Ball ball) {
ball.visited = true;
var result = new List () { ball };
var n = BallActiveNeighbors (ball);

foreach (var b in n) {
if (b.type == ball.type) {
result.Add (b);
}
}

return result;
}

void AddMatches (List matches) {
foreach (var b in matches) {
if (!matchList.Contains (b))
matchList.Add (b);
}
}

List BallActiveNeighbors (Ball ball) {
var result = new List ();
if (ball.column + 1 < COLUMNS) { if (gridBalls [ball.row] [ball.column + 1].gameObject.activeSelf) result.Add (gridBalls [ball.row] [ball.column + 1]); } //left if (ball.column - 1 >= 0) {
if (gridBalls [ball.row] [ball.column - 1].gameObject.activeSelf)
result.Add (gridBalls [ball.row] [ball.column - 1]);
}
//top
if (ball.row - 1 >= 0) {
if (gridBalls [ball.row - 1] [ball.column].gameObject.activeSelf)
result.Add (gridBalls [ball.row - 1] [ball.column]);
}

//bottom
if (ball.row + 1 < ROWS) { if (gridBalls [ball.row + 1] [ball.column].gameObject.activeSelf) result.Add (gridBalls [ball.row + 1] [ball.column]); } return result; }

In this game however, the CheckMatchesForBall call is made from the Grid class the moment we add a new ball to the grid.

public void AddBall (Ball collisionBall, Bullet bullet) {

var neighbors = BallEmptyNeighbors(collisionBall);
var minDistance = 10000.0f;
Ball minBall = null;
foreach (var n in neighbors) {
var d = Vector2.Distance (n.transform.position, bullet.transform.position);
if ( d < minDistance ) { minDistance = d; minBall = n; } } bullet.gameObject.SetActive (false); minBall.SetType (bullet.type); minBall.gameObject.SetActive (true); CheckMatchesForBall (minBall); }

And that's it. In the next tutorial I'll take out any bubbles which are disconnected to the main grid after matches are removed.

Here is the project so far.