Bubble Shooter Game in Unity: Part 5

After shooting a new bubble collision is handled through Box2D and the 2D circle colliders in each of the bubbles and the bullet.

The Ball will handle collision this way:

void OnTriggerEnter2D(Collider2D other) {
if (other.tag == "bullet") {
var b = other.gameObject.GetComponent ();
grid.AddBall (this, b);
}

}

And the new logic in the Grid class:

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); } List BallEmptyNeighbors (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]);
}

return result;
}

AddBall will make the ball in the correct grid-cell visible and set it's type to be the same as the bullet's.

Here is the project so far.