0

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 OnMouseUp()
{
    Debug.Log("MouseUp");
    cursor.transform.position = Vector3.MoveTowards(cursor.position, OriginalPosition, 10f * Time.deltaTime);
}
2
  • Are you using a virtual cursor? if not, could I assume that the cursor is just a game object and has no relation to your mouse cursor?
    – Nefisto
    Nov 13, 2022 at 11:54
  • @Nefisto Yes, the cursor is just a game object
    – Ilya
    Nov 13, 2022 at 12:00

1 Answer 1

1

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

1
  • 1
    Change OriginalPosition.position to OriginalPosition, otherwise it gives an error
    – Ilya
    Nov 13, 2022 at 12:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.