Dear Community,
You all know games like “Bejeweled” or “Candy Crush”. I am trying to copy it, as a learning experience. But a little different. I have a grid like this:
I don’t move tiles. Instead if I click on one tile I want the game to detect what color it is. Then I want all the horizontal and vertical neighbors of the same color to be detected and their neighbors of the same color too. Like a cascade. So lets say I click on the sun at the bottom right of the picture, I want all 3 suns at the bottom right to be detected, grouped and deactivated.
I have come as far as grouping the immediate neighbors of the clicked tile. But if I repeat the same procedure for the neighbors neighbor using a recursive method I get a “Stack Overflow” Error.
This is my code. This script is attached to each tile on the game board:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Element : MonoBehaviour {
public LayerMask elementLayer;
public bool hasBeenChecked;
private LayerMask familyLayer;
private List<Element> family = new List<Element> ();
void OnMouseDown ()
{
Debug.Log ("Mouse has been clicked on: " + this.transform.position);
familyLayer = this.elementLayer;
CheckNeighbours (this.transform.position);
}
void CheckNeighbours(Vector2 newPos)
{
Collider2D[] collidersInRange =
Physics2D.OverlapBoxAll (newPos, new Vector2 (1f, 1f), 45f, familyLayer);
foreach (Collider2D col in collidersInRange)
{
if (!hasBeenChecked) {
Element elemToCheck = col.GetComponent<Element> ();
family.Add (elemToCheck);
elemToCheck.hasBeenChecked = true;
CheckNeighbours (elemToCheck.transform.position);
}
}
}
}
My approach using a recursive method doesn’t seem to work. I have run out of ideas, as to how to program this game. I would greatly appreciate your support.
Thanks.