Hello i am currently working on a menu, so we are talking GUI elements, where when you click on one folder the others move away, so there is room for the chosen folder to open.
But i cannot find out how to smoothly move the folders around.
I have tried using MoveTowards and Lerp, but it does not work.
I have left my code both for Lerp and for MoveTowards so you can see.
Note This code is run in a coroutine.
//if the folder is not open...
if (!isFolderOpen)
{
//Check every RectTransform in the children list...
foreach (RectTransform child in children)
{
//and check if it's x position is bigger then the currently clicked folder
if (child.anchoredPosition.x > rect.anchoredPosition.x)
{
newPos = new Vector2(child.anchoredPosition.x - distance, child.anchoredPosition.y);
while (child.anchoredPosition != newPos)
{
//child.anchoredPosition = Vector2.MoveTowards(child.anchoredPosition, newPos, 10 * Time.deltaTime);
//child.anchoredPosition = new Vector2(Mathf.Lerp(child.anchoredPosition.x, child.anchoredPosition.x - distance, 0.5f), child.anchoredPosition.y);
yield return null;
}
Update
I can now make the folders move, but the movement is not stable. The first couple of times you open and close the folders everything looks great, but after a couple of clicks, the folders start shaking and suddenly move out instead of in.
Here is the new code:
private IEnumerator MoveOut(RectTransform folder, bool left) //Moves the folders outwards away from the selected folder
{
//Creates a variable to store the new position of the folder
Vector3 newPosChild;
//should it move left?
if (left)
{
//then set the new position to it's current position minus distance
newPosChild = new Vector3(folder.localPosition.x - distance, folder.localPosition.y, folder.localPosition.z);
}
//or should it move to the right?
else
{
//then set the new position to it's current position plus distance
newPosChild = new Vector3(folder.localPosition.x + distance, folder.localPosition.y, folder.localPosition.z);
}
//As long as the folder is not in it's new position...
while (folder.localPosition != newPosChild)
{
//move it towards it's new position
folder.localPosition = Vector3.MoveTowards(folder.localPosition, newPosChild, movementSpeed * Time.deltaTime);
if (Vector3.Distance(folder.localPosition, newPosChild) < 10)
{
folder.localPosition = newPosChild;
}
yield return null;
}
}
private IEnumerator MoveBack(RectTransform folder)
{
StoreOriginalPosition childOriPos;
childOriPos = folder.gameObject.GetComponent<StoreOriginalPosition>();
while (folder.localPosition != childOriPos.originalPos)
{
//move it back to it's original position
folder.localPosition = Vector3.MoveTowards(folder.localPosition, childOriPos.originalPos, movementSpeed * Time.deltaTime);
if (Vector3.Distance(folder.localPosition, childOriPos.originalPos) < 10)
{
folder.localPosition = childOriPos.originalPos;
}
yield return null;
}
}