I want to save the initial position of the cursor
at start, and after the cursor
has been moved and the mouse button is released, it should return to its original position (using 10f * Time.deltaTime
), but this does not work
[SerializeField] private Transform cursor;
private Vector3 OriginalPosition;
void Start()
{
OriginalPosition = cursor.transform.position;
Debug.Log(OriginalPosition);
}
void onm ouseUp()
{
Debug.Log("MouseUp");
cursor.transform.position = Vector3.MoveTowards(cursor.position, OriginalPosition, 10f * Time.deltaTime);
}
CodePudding user response:
The problem is that you are assuming that calling a MoveForward will make your game object follow all its way back to the original position, which will not happen, what you're actually doing is saying to your cursor "when I release my mouse button, calculate the direction between my current position and original position and with a speed of 10 units per second move the amount that it would be in 1 frame". What you need is to make the MoveToward operation during the period of N frames, for making this happen you need to use a coroutine, so follow a similar code
public Transform cursor;
public Transform originalPosition;
public void Move()
{
StartCoroutine(MoveToTargetPosition());
IEnumerator MoveToTargetPosition()
{
while (Vector3.Distance(cursor.position, originalPosition.position) >= .5f)
{
yield return null;
cursor.position = Vector3.MoveTowards(cursor.position, originalPosition.position, 10f * Time.deltaTime);
}
}
}
Hope this help