- Home /
How to check connection?
So I'm creating puzzle-like game (on screens) and I have no idea how to check if the start object is connected (using other objects) with the finish object. This is just example, so it won't always be straight line. Starting with this:
I want my game to detect when this happens.
There is no grid, elements are simple gameobjects with colliders.
Answer by Kiwasi · Jan 11, 2015 at 07:10 AM
There are two parts to this. First you need a method to find all cells that are connected to a single cell.
Second you walk the graph, starting with the first cell. Pseudo code as follows
List<Cells> connectedCells;
List<Cells> visitedCells;
connectedCells.Add(FirstCell);
while (connectedCells.Count > 0){
Cell[] neighbours = connectedCells[0].cell.findAllNeighbours;
foreach (Cell neighbour in neighbours){
if (!visitedCells.Contains(neighbour){
if (neighbour == finalDestination) return true;
connectedCells.Add (neighbour);
}
}
visitedCells.Add(connectedCells[0]);
connectedCells.RemoveAt(0);
}
return false;
For the real application a queue or stack is more efficient then a List. If the graph is large then a graph search or path finding algorithm like Dijkstra or A* may be more efficient.
Your answer
