I have been trying to implement the Wave Function Collapse(link) Algorithm in Unity using Best first search.
For this I use various helper classes,namely:
Wave_Tiles.cs
using UnityEngine;
using UnityEngine.Tilemaps;
using System.Collections.Generic;
[CreateAssetMenu(menuName = "2D/Tiles/WaveFunctionTiles")]
public class Wave_Tiles : ScriptableObject
{
public bool ongroundtilemap;
public TileBase tiletoinstantiate;
public List<Wave_Tiles> up;
public List<Wave_Tiles> down;
public List<Wave_Tiles> left;
public List<Wave_Tiles> right;
}
This class stores the information for the tiles to use.The tiletoinstantiate is the actual tile that is to be put in the place and its valid neighbours are storedd in the respective lists.
Node.cs
using UnityEngine;
using UnityEngine.Tilemaps;
using System.Collections.Generic;
[System.Serializable]
public class Nodes
{
public bool iscollapsed;
public Vector3Int position;
public List<TileBase> ValidTiles;
public Nodes(Vector3Int pos)
{
position = pos;
ValidTiles = new List<TileBase>();
}
public Nodes(int x, int y)
{
position = new Vector3Int(x, y, 0);
ValidTiles = new List<TileBase>();
}
public TileBase coll(Tilemap ground)
{
if (iscollapsed)
return null;
iscollapsed = true;
TileBase tmp = null;
if (ValidTiles.Count > 0)
{
int rand = Random.Range(0, ValidTiles.Count);
ground.SetTile(position, ValidTiles[rand]);
tmp = ValidTiles[rand];
}
return tmp;
}
public override bool Equals(object obj)
{
if (obj == null)
return false;
if (obj is Nodes)
return Equals(obj as Nodes);
return false;
}
public override int GetHashCode()
{
return position.x ^ position.y;
}
public bool Equals(Nodes obj)
{
if (obj == null)
{
return false;
}
return (position.x == obj.position.x) && (position.y == obj.position.y);
}
}
This class is used to traverse the grid and stores the valid tiles for the position.The collapse function collapses on a random tile from the ValidTile List.
Wave_Func.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Tilemaps;
using System.Linq;
public class Wave_Func : MonoBehaviour
{
public bool working;
public float wait_time;
public Tilemap Grid;
public Vector2Int LimitsMin, LimitsMax;
public Nodes startNode;
WaitForSeconds wait;
public List<Wave_Tiles> Game_Tiles;
public List<Nodes> Openlist, ClosedList, openneighbour, closedneighbour;
private void Start()
{
StartCoroutine(wavefunccoll());
}
public IEnumerator wavefunccoll()
{
working = true;
wait = new WaitForSeconds(wait_time);
Openlist.Add(startNode);
yield return wait;
while (Openlist.Count > 0)
{
Nodes current = Openlist[0];
Openlist.Remove(current);
ClosedList.Add(current);
yield return wait;
yield return StartCoroutine(collapse(current));
Openlist = Openlist.OrderBy(a => a.ValidTiles.Count).ToList();
}
working = false;
}
IEnumerator collapse(Nodes current)
{
closedneighbour.Clear();
yield return null;
TileBase parenttofind = current.coll(Grid);
Wave_Tiles parent = null;
foreach (Wave_Tiles wtf in Game_Tiles)
if (wtf.tiletoinstantiate == parenttofind)
{
parent = wtf;
break;
}
if (parent != null)
foreach (Nodes neighbour in getneighbours(current, parent))
{
if (openneighbour.Contains(neighbour))
openneighbour.RemoveAll(item => item == neighbour);
openneighbour.Add(neighbour);
}
yield return null;
while (openneighbour.Count > 0)
{
current = openneighbour[0];
openneighbour.Remove(current);
closedneighbour.Add(current);
foreach (Wave_Tiles wtf in Game_Tiles)
if (wtf.tiletoinstantiate == parenttofind)
{
parent = wtf;
break;
}
yield return null;
foreach (Nodes neighbour in getneighbours(current))
{
if (openneighbour.Contains(neighbour))
openneighbour.RemoveAll(item => item == neighbour);
openneighbour.Add(neighbour);
}
}
foreach (Nodes neighbour in closedneighbour)
{
yield return null;
if (Openlist.Contains(neighbour))
Openlist.RemoveAll(item => item == neighbour);
Openlist.Add(neighbour);
}
}
List<Nodes> getneighbours(Nodes current, Wave_Tiles parent)
{
List<Nodes> neighbours = new List<Nodes>();
Vector3Int curpos;
for (int i = -1; i < 2; i++)
{
for (int j = -1; j < 2; j++)
{
if ((i == 0 && j == 0) || (Mathf.Abs(i) + Mathf.Abs(j) == 2))
continue;
curpos = current.position + new Vector3Int(i, j);
if (curpos.x >= LimitsMax.x || curpos.x < LimitsMin.x || curpos.y >= LimitsMax.y || curpos.y < LimitsMin.y)
continue;
Nodes neighbour = new Nodes(curpos);
if (ClosedList.Contains(neighbour))
continue;
if (Openlist.Contains(neighbour))
neighbour = Openlist[Openlist.IndexOf(neighbour)];
List<TileBase> inter = null;
if (i == 1 && j == 0)
{
if (parent.right == null)
continue;
if (neighbour.ValidTiles.Count < 1)
{
foreach (Wave_Tiles wtf in parent.right)
neighbour.ValidTiles.Add(wtf.tiletoinstantiate);
}
else
{
inter = new List<TileBase>();
foreach (Wave_Tiles wtf in parent.right)
if (neighbour.ValidTiles.Contains(wtf.tiletoinstantiate))
inter.Add(wtf.tiletoinstantiate);
}
}
if (i == -1 && j == 0)
{
if (parent.left == null)
continue;
if (neighbour.ValidTiles.Count < 1)
{
foreach (Wave_Tiles wtf in parent.left)
neighbour.ValidTiles.Add(wtf.tiletoinstantiate);
}
else
{
inter = new List<TileBase>();
foreach (Wave_Tiles wtf in parent.left)
if (neighbour.ValidTiles.Contains(wtf.tiletoinstantiate))
inter.Add(wtf.tiletoinstantiate);
}
}
if (i == 0 && j == -1)
{
if (parent.down == null)
continue;
if (neighbour.ValidTiles.Count < 1)
{
foreach (Wave_Tiles wtf in parent.down)
neighbour.ValidTiles.Add(wtf.tiletoinstantiate);
}
else
{
inter = new List<TileBase>();
foreach (Wave_Tiles wtf in parent.down)
if (neighbour.ValidTiles.Contains(wtf.tiletoinstantiate))
inter.Add(wtf.tiletoinstantiate);
}
}
if (i == 0 && j == 1)
{
if (parent.up == null)
continue;
if (neighbour.ValidTiles.Count < 1)
{
foreach (Wave_Tiles wtf in parent.up)
neighbour.ValidTiles.Add(wtf.tiletoinstantiate);
}
else
{
inter = new List<TileBase>();
foreach (Wave_Tiles wtf in parent.up)
if (neighbour.ValidTiles.Contains(wtf.tiletoinstantiate))
inter.Add(wtf.tiletoinstantiate);
}
}
if (inter != null)
neighbour.ValidTiles = inter;
neighbours.Add(neighbour);
}
}
return neighbours;
}
List<Nodes> getneighbours(Nodes current)
{
List<Nodes> neighbours = new List<Nodes>();
Vector3Int curpos;
for (int i = -1; i < 2; i++)
{
for (int j = -1; j < 2; j++)
{
if ((i == 0 && j == 0) || (Mathf.Abs(i) + Mathf.Abs(j) == 2))
continue;
curpos = current.position + new Vector3Int(i, j);
if (curpos.x >= LimitsMax.x || curpos.x < LimitsMin.x || curpos.y >= LimitsMax.y || curpos.y < LimitsMin.y)
continue;
Nodes neighbour = new Nodes(curpos);
if (ClosedList.Contains(neighbour) || closedneighbour.Contains(neighbour) || Openlist.Contains(neighbour))
continue;
if (openneighbour.Contains(neighbour))
neighbour = openneighbour[openneighbour.IndexOf(neighbour)];
neighbours.Add(neighbour);
}
}
return neighbours;
}
}
This class implements the main logic of the algorithm. So the startnode is populated with all the tiles from Game_Tiles and is added to the Openlist which runs a Best first Search and collapses the tile that has the least Count of ValidTiles. The collapse Function randomly choses a tile and "Collapses" the current tile after which it finds the rules for this tile and populates its neighbours' validlist and adds it to the openneighbour.
So my question is that Can I achieve the Wave function collapse using the above mentioned technique?
If so could you please point out the problems with this script/technique and some ways to fix it.
Thanks in advance.
Related
I am trying to make the tic tac toe game in C# Windows Forms using the minimax algorithm as the opponent. So instead of making the best move, like preventing the player from winning or playing a move that allows it to get closer to winning, it moves to the following empty index on the board. So how could I fix the algorithm?
int evaluate(int[] grid)
{
for(int i = 0; i < 9; i += 3)
{
if (grid[i] == 0) continue;
if (grid[i] == grid[i + 1] && grid [i] == grid[i + 2])
return grid[i]==1 ? 10 :-10;
}
for (int i = 0; i < 3; i++)
{
if (grid[i] == 0) continue;
if (grid[i] == grid[i + 3] && grid[i] == grid[i + 6])
return grid[i] == 1 ? 10 : -10;
}
if ((grid[0] == grid[4] && grid[4] == grid[8]) || (grid[2] == grid[4] && grid[4] == grid[6]))
return grid[4] == 1 ? 10 : -10;
return 0;
}
bool isMovesLeft(int[] grid)
{
for(int i = 0; i< grid.Length; i++)
{
if (grid[i] == 0) return true;
}
return false;
}
int miniMax(int[] grid,int depth, bool isMax)
{
int isWon = evaluate(grid);
if (isWon == 10 || isWon == -10)
return isWon;
if(!isMovesLeft(grid))
return 0;
if (isMax)
{
int best = int.MinValue;
for(int i = 0;i< grid.Length;i++)
{
if (grid[i] == 0)
{
grid[i] = 1;
best = Math.Max(best,miniMax(grid, depth+1, !isMax));
grid[i] = 0;
}
}
return best;
}
else
{
int best = int.MaxValue;
for (int i = 0; i < grid.Length; i++)
{
if (grid[i] == 0)
{
grid[i] = 2;
best = Math.Min(best, miniMax(grid, depth+1, !isMax));
grid[i] = 0;
}
}
return best;
}
}
void moveByAI()
{
int best = int.MinValue;
int move = -1;
for(int i =0; i<9;i++)
{
if (grids[i]==0)
{
grids[i] = 2;
int locValue = miniMax(grids, 0, true);
grids[i] = 0;
if(locValue > best)
{
move = i;
best = locValue;
MessageBox.Show(""+i);
}
}
}
buttons[move].PerformClick();
}
The snake head 0 does not move anywhere when Console.ReadKey() happens.
Here is the full code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SimpleSnakeGame_ConsoleApp
{
internal class Program
{
public bool gameOver = true;
public int width = 20;
public int height = 20;
//HEAD POS
public int x, y;
//FRUIT POS
public int fruitX, fruitY;
public int score;
//bir kere basınca oraya gitmeni sağlayacak enum
enum eDirection { STOP = 0, LEFT, RIGHT, UP, DOWN };
eDirection dir; //enum class gibi çalışıyor enum'dan dir isimli bir object yarattık
static void Main(string[] args)
{
Program oyun = new Program();
oyun.Setup();
oyun.Draw();
oyun.Input();
oyun.Logic();
Console.ReadLine();
}
//Setting Up the MAP
public void Setup()
{
gameOver = false;
string a = "!!!!! SİMPLE SNAKE GAME !!!!!";
Console.WriteLine(gameOver.ToString() + " " + a, "{0}" + "{1}");
dir = eDirection.STOP;
x = width / 2;
y = height / 2;
Random rnd = new Random();
fruitX = rnd.Next(1, 19);
fruitY = rnd.Next(1, 19);
score = 0;
}
void Draw()
{
for (int j = 0; j < height; j++)
{
for (int i = 0; i < width; i++)
{
if (i == y && j == x)
{
Console.Write("0");
}
else if (i == fruitY && j == fruitX)
{
Console.Write("F");
}
else if (j > 0 && j < height - 1 && i > 0 && i < width - 1)
{
Console.Write(" ");
}
else
{
Console.Write("#");
}
}
Console.WriteLine();
}
Console.WriteLine();
}
void Input()
{
ConsoleKey key;
// Key is available - read it
key = Console.ReadKey(true).Key;
if (key == ConsoleKey.A)
{
dir = eDirection.LEFT;
}
else if (key == ConsoleKey.D)
{
dir = eDirection.RIGHT;
}
else if (key == ConsoleKey.W)
{
dir = eDirection.UP;
}
else if (key == ConsoleKey.S)
{
dir = eDirection.DOWN;
}
else if (key == ConsoleKey.X)
{
gameOver=true;
}
}
void Logic()
{
switch (dir)
{
case eDirection.LEFT:
x--;
break;
case eDirection.RIGHT:
x++;
break;
case eDirection.UP:
y--;
break;
case eDirection.DOWN:
y++;
break;
default:
break;
}
}
}
}
I guess the problem is Console.ReadKey() function here:
void Input()
{
ConsoleKey key;
// Key is available - read it
key = Console.ReadKey(true).Key;
if (key == ConsoleKey.A)
{
dir = eDirection.LEFT;
}
else if (key == ConsoleKey.D)
{
dir = eDirection.RIGHT;
}
else if (key == ConsoleKey.W)
{
dir = eDirection.UP;
}
else if (key == ConsoleKey.S)
{
dir = eDirection.DOWN;
}
else if (key == ConsoleKey.X)
{
gameOver=true;
}
}
However I do not know what to replace Console.ReadKey() with and how to do it.
Here is the OUTPUT:
You are correct about Console.ReadKey() being the problem as it is blocking and will pause the game until a key is pressed.
You will need to do something like this:
if (Console.KeyAvailable)
{
ConsoleKeyInfo key = Console.ReadKey(true);
// process key here
}
This way you are reading from the console without blocking until a key is pressed.
Hello I trying to do a QuickSort but didn't appear the result, For example the user input "cdabe" so the expected result is "abcde". May I know what is the cause why the result didn't display?
because There is no error in the code. I'm using MVC. My MergeSort is working properly but my QuickSort didn't.
Model :
public string QuickSort()
{
string arrangedSort = "";
string Word= "cdabe";
List<string> ListLetters = new List<string>();
for (int i = 0; i < Word.Length; i++)
{
ListLetters.Add(Word.Substring(i, 1));
}
aQuicksort(Word, 0, ListLetters.Count - 1);
void aQuicksort(string Word, int left, int right)
{
int i = left;
int j = right;
var pivot = Word[(left + right) / 2];
while (i <= j)
{
while (char.Parse(ListLetters[i]) < pivot)
i++;
while (char.Parse(ListLetters[i]) > pivot)
j--;
if (i <= j)
{
var tmp = ListLetters[i];
ListLetters[i] = ListLetters[j];
ListLetters[j] = tmp;
i++;
j--;
}
}
if (left < j)
aQuicksort(Word, left, j);
if (i < right)
aQuicksort(Word, i, right);
foreach (var listLetter in ListLetters)
{
arrangedSort += listLetter;
}
}
return arrangedSort;
}
Try this implementation, it uses LinQ using System.linq
public static IEnumerable<int> QSort3(IEnumerable<int> source)
{
if (!source.Any())
return source;
int first = source.First();
QSort3Helper myHelper =
source.GroupBy(i => i.CompareTo(first))
.Aggregate(new QSort3Helper(), (a, g) =>
{
if (g.Key == 0)
a.Same = g;
else if (g.Key == -1)
a.Less = g;
else if (g.Key == 1)
a.More = g;
return a;
});
IEnumerable<int> myResult = Enumerable.Empty<int>();
if (myHelper.Less != null)
myResult = myResult.Concat(QSort3(myHelper.Less));
if (myHelper.Same != null)
myResult = myResult.Concat(myHelper.Same);
if (myHelper.More != null)
myResult = myResult.Concat(QSort3(myHelper.More));
return myResult;
}
public class QSort3Helper
{
public IEnumerable<int> Less;
public IEnumerable<int> Same;
public IEnumerable<int> More;
}
code from this post
I'm trying to come up with my "own" a* pathfinding algorithm following the explanation of this article : https://www.redblobgames.com/pathfinding/a-star/introduction.html
But it seems that my pathfinding code runs into some sort of infinte-while-loop which inmediatly crashes Unity. But I honestly do not know what am I doing wrong
Here's my code
EDIT : it seems that unity editor crashes due to an OutOfMemory exception. I do not know what is going on
public class PathFinding {
List<PathNode> openList;
List<PathNode> closedList;
Grid_Ian<PathNode> grid;
public PathFinding(Grid_Ian<PathNode> grid)
{
openList = new List<PathNode>();
closedList = new List<PathNode>();
this.grid = grid;
}
public List<PathNode> makePath(PathNode startNode, PathNode endNode)
{
if (startNode == null || endNode == null)
{
return new List<PathNode>();
}
if(grid.getGridObject(startNode.x,startNode.y) == null
|| grid.getGridObject(endNode.x, endNode.y) == null)
{
return new List<PathNode>();
}
startNode.hCost = calculateDistanceCost(startNode, endNode);
startNode.gCost = 0;
startNode.calculateFCost();
startNode.cameFrom = null;
openList.Add(startNode);
PathNode currentNode = startNode;
while (openList.Count > 0)
{
Debug.Log("LOOPING");
currentNode = getLowestFcost(openList);
openList.Remove(currentNode);
closedList.Add(currentNode);
if (currentNode.x == endNode.x &&
currentNode.y == endNode.y)
{
return getPath(currentNode);
}
foreach (PathNode next in getNeighbors(currentNode))
{
int newCost = currentNode.fCost + calculateDistanceCost(currentNode, next);
if (closedList.Contains(next)) continue;
if (next.cameFrom == null || newCost < next.fCost)
{
Debug.Log("NUEVO VECINO");
int nextCost = calculateDistanceCost(currentNode, next);
next.gCost = currentNode.gCost + nextCost;
next.hCost = currentNode.hCost + nextCost;
next.calculateFCost();
next.cameFrom = currentNode;
openList.Add(next);
}
}
}
return new List<PathNode>();
}
public List<PathNode> getNeighbors(PathNode currentNode)
{
List<PathNode> neighborNodes = new List<PathNode>();
if (currentNode.x - 1 >= 0)
{
//left
neighborNodes.Add(getNode(currentNode.x - 1, currentNode.y));
}
if (currentNode.x + 1 >= 0)
{
//right
neighborNodes.Add(getNode(currentNode.x + 1, currentNode.y));
}
//up
if (currentNode.y + 1 >= 0)
{
neighborNodes.Add(getNode(currentNode.x, currentNode.y + 1));
}
//down
if (currentNode.y - 1 >= 0)
{
neighborNodes.Add(getNode(currentNode.x, currentNode.y - 1));
}
return neighborNodes;
}
public PathNode getNode(int x, int y)
{
if(grid.getGridObject(x,y) == null)
{
}
return grid.getGridObject(x, y);
}
private PathNode getLowestFcost(List<PathNode> nodeList)
{
PathNode lowestNode = getNode(0,0); // TODO : ARREGLAR
int fCost = 0;
foreach (PathNode node in nodeList)
{
if (fCost > node.fCost)
{
fCost = node.fCost;
lowestNode = node;
}
}
return lowestNode;
}
private int calculateDistanceCost(PathNode a, PathNode b)
{
return Mathf.Abs(a.x - b.x) + Mathf.Abs(a.y - b.y);
}
private List<PathNode> getPath(PathNode currentNode ){
List<PathNode> path = new List<PathNode>();
path.Add(currentNode);
while (currentNode.cameFrom != null)
{
currentNode = currentNode.cameFrom;
path.Add(currentNode);
}
path.Reverse();
return path;
}
public void getXY(Vector3 worldPosition, out int x, out int y)
{
grid.GetXY(worldPosition, out x, out y);
}
}
public class PathNode {
public int x, y;
public int hCost, gCost,fCost;
public PathNode cameFrom;
// G = start
// H = end
// F = G + H
public PathNode(int x,int y)
{
this.x = x;
this.y = y;
}
public void calculateFCost()
{
fCost = hCost + gCost;
}
}
I tried to check your Code with my and 2 Ideas you could try.
First is I think you shouldn't set the in the foreach the newCost before the if. So you could try:
foreach (PathNode next in getNeighbors(currentNode))
{
if (closedList.Contains(next)) continue;
int newCost = currentNode.fCost + calculateDistanceCost(currentNode, next);
if (next.cameFrom == null || newCost < next.fCost)
{
Debug.Log("NUEVO VECINO");
int nextCost = calculateDistanceCost(currentNode, next);
next.gCost = currentNode.gCost + nextCost;
next.hCost = currentNode.hCost + nextCost;
next.calculateFCost();
next.cameFrom = currentNode;
openList.Add(next);
}
}
Or one more thing. I have for some Reasons again a openList.Contains check before I add it to the openList. I do not know why again I did this but I think maybe you can try it, don't know if this helps. I made it quite a long time ago:
foreach (PathNode next in getNeighbors(currentNode))
{
int newCost = currentNode.fCost + calculateDistanceCost(currentNode, next);
if (closedList.Contains(next)) continue;
if (next.cameFrom == null || newCost < next.fCost)
{
Debug.Log("NUEVO VECINO");
int nextCost = calculateDistanceCost(currentNode, next);
next.gCost = currentNode.gCost + nextCost;
next.hCost = currentNode.hCost + nextCost;
next.calculateFCost();
next.cameFrom = currentNode;
if(!openList.Contains(next))
{
openList.Add(next);
}
}
}
I found two more things.
First your getNode function shouldn't look like this:
public PathNode getNode(int x, int y)
{
if(grid.getGridObject(x,y) == null)
{
}
return grid.getGridObject(x, y);
}
It should be:
public PathNode getNode(int x, int y)
{
if(grid.getGridObject(x,y) != null)
{
return grid.getGridObject(x, y);
}
return null; //need error handling
}
And the Second thing is for your getNeighbors. I do not know exactly how you create the Nodes, but for example they are in a Grid you should check if there is something for X and Y and not OutOfIndex.
Here my check out of my Code for one NeighborNode:
if (checkX >= 0 && checkX < gridSizeX)
{
if (checkY >= 0 && checkY < gridSizeY)
{
neighborList.Add(nodeArray[checkX, checkY]);
}
}
Because of getNode function you add to the openList NULL
I have searched the similar games on forum and google but i could not find exactly.
I am making a puzzle game. and user can get point if the nodes (horizontal sticks) are same color then he can get.
when they are in same direction it says colors matched but in generated node whenever i rotate the sticks it says also same.
Can you take a look? and tell me how to fix. Also if you have better idea about this matching I will be appreciated.
---------
void Update()
{
if (Input.GetMouseButtonDown(0))
{
clickTime = Time.time;
rayhit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero, Mathf.Infinity, selectableObjLayerMask);
}
else if (Input.GetMouseButtonUp(0))
{
if (rayhit)
{
if (Time.time - clickTime < .2f)
{
Node node = rayhit.transform.GetComponent<Node>();
if (node != null)
{
for (int i = 0; i < node.sticks.Count; i++)
{
Vector3 newAngles = new Vector3(0, 0, (node.sticks[i].transform.localEulerAngles.z - 45));
newAngles.z = newAngles.z < 0 ? newAngles.z + 180 : newAngles.z;
newAngles.z = newAngles.z >180 ? newAngles.z - 180 : newAngles.z;
node.sticks[i].transform.localEulerAngles = newAngles;
node.sticks[i].degree = (int)newAngles.z;
//******** HERE IS COLOR MATCHING*******
if (node.transform.parent.name=="Node1" && node.sticks[i].degree == 90)
{
colorMatch[1] = node.sticks[i].color;
Debug.Log("COLOR 1___"+ colorMatch[1]);
//Debug.Log(colorMatch1);
}
if (node.transform.parent.name == "Node2" && node.sticks[i].degree == 90)
{
colorMatch[2] = node.sticks[i].color;
Debug.Log("COLOR 2___" + colorMatch[2]);
}
if (node.transform.parent.name == "Node3" && node.sticks[i].degree == 90)
{
colorMatch[3] = node.sticks[i].color;
Debug.Log("COLOR 3___" + colorMatch[3]);
//if (colorMatch[1] == colorMatch[2] && colorMatch[2] == colorMatch[3])
//{
// Debug.Log("COLORS MATCHED : " + colorMatch[1]);
//}
}
if (colorMatch[1]==colorMatch[2] && colorMatch[2]==colorMatch[3])
{
Debug.Log("COLOR MATCHED");
}
}
}
}
else
{
Node currNode = rayhit.transform.GetComponent<Node>();
if(currNode.isMoved == false)
{
smallestId = 0;
smallestDistance = 999;
for (int i = 0; i < nodes.Length; i++)
{
float distance = Vector2.Distance(rayhit.transform.position, nodes[i].transform.position);
if (smallestDistance > distance)
{
smallestDistance = distance;
smallestId = i;
}
}
rayhit.transform.position = nodes[smallestId].transform.position;
if (rayhit.transform.parent != nodes[smallestId].transform)
{
if (nodes[smallestId].transform.childCount > 0 && nodes[smallestId].transform != rayhit.transform.parent)
{
if (currNode != null)
{
for (int i = 0; i < currNode.sticks.Count; i++)
{
nodes[smallestId].transform.GetChild(0).GetComponent<Node>().sticks.Add(currNode.sticks[i]);
currNode.sticks[i].transform.SetParent(nodes[smallestId].transform.GetChild(0));
}
Destroy(rayhit.transform.gameObject);
}
}
else
{
if (currNode != null)
{
currNode.isMoved = true;
}
rayhit.transform.SetParent(nodes[smallestId].transform);
}
}
}
}
}
rayhit = new RaycastHit2D();
}
else if (Input.GetMouseButton(0))
{
if(rayhit.transform != null)
{
Node currNode = rayhit.transform.GetComponent<Node>();
if(currNode != null)
if (currNode.isMoved == false)
{
if (Time.time - clickTime >= 0.2f)
{
Vector2 newPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
rayhit.transform.position = newPos;
}
}
}
}
}
if (node.transform.parent.name=="Node1" && node.sticks[i].degree == 90)
{
colorMatch[1] = node.sticks[i].color;
Debug.Log("COLOR 1___"+ colorMatch[1]);
//Debug.Log(colorMatch1);
}
if (node.transform.parent.name == "Node2" && node.sticks[i].degree == 90)
{
colorMatch[2] = node.sticks[i].color;
Debug.Log("COLOR 2___" + colorMatch[2]);
}
if (node.transform.parent.name == "Node3" && node.sticks[i].degree == 90)
{
colorMatch[3] = node.sticks[i].color;
Debug.Log("COLOR 3___" + colorMatch[3]);
if (colorMatch[1] == colorMatch[2] && colorMatch[2] == colorMatch[3])
{
Debug.Log("COLORS MATCHED : " + colorMatch[1]);
}
}
Here is working code. but how i can destroy the matched sticks?