Move player on predetermined looping path

Hi all,

I am a begginer developer and I am having difficulties coding the following problem( 2D):

  1. While the button down is pressed, the player should move:
  2. from the starting position down -2 spaces
  3. then up 2 spaces
  4. loop this down 2, up 2 spaces until the button is released
  5. Continue on the current y coordinate (x never changes)
  6. when pressed again, the movement should repeat from the new y coord.

The opposite should work if button Up is pressed.

If tried implementing it with Mathf.Sin(Time.time), but if I repeat the button press, instead of restarting and going down, it remembers the last played position and continues going i.e. up, instead of starting down.

Any help is very much appreciated!

Damn, I’ll write you some code :stuck_out_tongue:

    public void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
            StartCoroutine(MoveOnPath(currentIndex));
    }

    [Header("Movement")]
    public float moveSpeed = 10;
    public float maxDistanceToTarget = 0.2f;
    public bool autoContinue;
    public bool isRelativeMovement; // Relative to players position
    [Space]
    public Vector2[] path;
    int currentIndex;

    public IEnumerator MoveOnPath(int pathIndex)
    {
        currentIndex = pathIndex;

        if (path.Length <= pathIndex) // Stops the Courotine if the pathIndex is higher than the counter of the path positions
            yield break;

        Vector2 tarPos = path[currentIndex];
        if (isRelativeMovement)
            tarPos += (Vector2)transform.position;

        while (Vector2.Distance(transform.position, tarPos) > maxDistanceToTarget) // Moves to target as long as the position is out of reach (maxDistanceToTarget)
        {
            transform.position = Vector3.MoveTowards(transform.position, tarPos, Time.deltaTime * moveSpeed);
        }

        int nextIndex = currentIndex++;
        if(nextIndex >= path.Length)
            nextIndex = 0; // If the last point is reached it restarts from the beginning

        if (autoContinue)
            StartCoroutine(MoveOnPath(nextIndex)); // Restarts the whole process with the next waypoint!
    }