Hello everyone, I am quite new to Unity and C# and want some help if anyone knows.
I am trying to create a simple “Tower of Hanoi” game and I don’t know how to parameterize and store the available targets a ring can move to.
For example if a ring is on pole A, available targets should be B or C or if it is on pole B, available targets should be on pole A or C. I am moving the ring with void OnMouseDrag() function and thinking that the right place to update the ring position and available targets is on void MouseUp() function.
You’ll need a script to keep track of which Rings are on which poles:
public class RingPositions : MonoBehaviour
{
public static List<Ring>[] poles = new List<Ring>[3] { new List<Ring>(), new List<Ring>(), new List<Ring>() };
}
And a script attached to each ring. Something like this:
public class Ring : MonoBehaviour
{
public int size = 0; // The size of the ring. Larger value = bigger ring
public int poleNumber = 1; // The pole number this ring is on. Either 1, 2 or 3
bool isBeingDragged = false;
void Start ()
{
RingPositions.poles[poleNumber].Add(this as Ring);
}
void OnMouseDown ()
{
// Find the minimum ring size on this pole
int minSize = 99999;
foreach (Ring r in RingPositions.poles[poleNumber])
{
if (r.size < minSize)
{
minSize = r.size;
}
}
// Can only move the ring if it is the minimum size ring on the pole
if (size == minSize)
{
isBeingDragged = true;
}
}
void OnMouseDrag ()
{
if (isBeingDragged)
{
// Update position of this object to follow the mouse
}
}
void OnMouseUp ()
{
// Find the position of the nearest pole
int nearestPoleNumber = ..... ; // Either 1, 2 or 3
// Make sure we have dragged it to different pole
if (poleNumber != nearestPoleNumber)
{
// Find the smallest ring on the new pole
int minSize = 99999;
foreach (Ring r in RingPositions.poles[nearestPoleNumber])
{
if (r.size < minSize)
{
minSize = r.size;
}
}
// This ring must be smaller if we can put it on this pole
if (size < minSize)
{
RingPositions.poles[poleNumber].Remove(this as Ring);
RingPositions.poles[nearestPoleNumber].Add(this as Ring);
// Change the position to the new pole
} else
{
// Change position back to the pole it was on
}
} else
{
// Change position back to the pole it was on
}
isBeingDragged = false;
}
}
This keeps track of the size of each ring and doesn’t allow for placing large rings onto smaller ones. You’ll have to fill in the gaps, updating the rings positions when being dragged or moved to the new ring or being moved back to the old ring.
You also need a way of finding which pole is nearest when you drop the ring. I suggest using a gameObject for each pole and Vector3.Distance to find the nearest.